How to Move an Array Element from One Array Position to Another
In this JavaScript tutorial, you will read and learn information about an easy insert strategy method of moving the array element to another position.
In this tutorial, you will find an insert strategy of moving an array element to another position.
Handling the issue is possible with a custom arrMove function that moves the item to the new position:
Javascript returns a new array with the item moved to the new position
The return arr; statement is necessary to output the modified array from the function. Since <kbd class="highlighted">splice()</kbd> mutates the array in-place, the function returns the same reference. If you want to avoid mutating the original array and return a copy instead, you can pass a copy created with the slice() method.
If newIndex is greater than the array length, you should pad the array with undefined. Setting arr.length = newIndex + 1 automatically fills the gap with undefined values.
Then you should splice out the old item. The <kbd class="highlighted">splice()</kbd> method returns the removed items in an array. Since in the given example the removed item is 11, you access the first element [0] to get the raw value 11.
Then you should use <kbd class="highlighted">splice()</kbd> to insert this item at the newIndex position. As you have already padded the array, it will appear in the correct place.
For negative indexes use the following code piece:
Javascript new array splice item to the new position
The splice() Method
The <kbd class="highlighted">Array.prototype.splice()</kbd> method changes the content of an array by removing or replacing existing items or adding new items in place. Unlike the <kbd class="highlighted">slice()</kbd> method, <kbd class="highlighted">splice()</kbd> changes the original array.
The slice() Method
The <kbd class="highlighted">Array.prototype.slice()</kbd> 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.