In this tutorial, you will find an insert strategy of moving an array element to another position.
Handling the issue is possible with the array-move method which returns a new array with the item moved to the new position:
The last return is for testing purposes. The splice() method performs operations on the array in-place, so a return is not necessary. If you want to avoid it and return a copy, you can use the slice() method.
Then you should splice out the old item. The splice() method returns the item that was spliced out in an array. Since in the given example, this was , you should take the first index of that array to get the raw 1.
Then you should use splice() to insert this item in the newIndex's place. As you have already padded the array, it will appear in the right place.
For negative indexes use the following code piece:
The Array.prototype.splice() method changes the content of an array by removing or replacing existing items or adding new items in place. Unlike the slice() method,slice() changes the original array.
The Array.prototype.slice() method returns a new array copying to it all the items from index start to the end (but the end is not included) where start and end represent the index of items in that array. The original array remains unchanged.