How to Move an Array Element from One Array Position to Another

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:

Javascript returns a new array with the item moved to the new position
function arrMove(arr, oldIndex, newIndex) { if (newIndex >= arr.length) { let i = newIndex - arr.length + 1; while (i--) { arr.push(undefined); } } arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]); return arr; }; // returns [22, 11, 33] console.log(arrMove([11, 22, 33], 0, 1));

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.

If newIndex is greater than the array length, you should pad the array with new undefined. It will push undefined on the array until you have the proper length.

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 [1], 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:

Javascript new array splice item to the new position
function arrayMove(arr, oldIndex, newIndex) { while (oldIndex < 0) { oldIndex += arr.length; } while (newIndex < 0) { newIndex += arr.length; } if (newIndex >= arr.length) { let i = newIndex - arr.length + 1; while (i--) { arr.push(undefined); } } arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]); return arr; }; // returns [11, 33, 22] console.log(arrayMove([11, 22, 33], -1, -2));

The splice() Method

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 slice() Method

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.