I’m having a hard time figuring out how to move an element of an array. For example, given the following:
var array = [ 'a', 'b', 'c', 'd', 'e'];
How can I write a function to move the element 'd' to the left of 'b' ?
Or 'a' to the right of 'c'?
After moving the elements, the indexes of the rest of the elements should be updated. The resulting array would be:
array = ['a', 'd', 'b', 'c', 'e']
This seems like it should be pretty simple, but I can’t wrap my head around it.
If you’d like a version on npm, array-move is the closest to this answer, although it’s not the same implementation. See its usage section for more details. The previous version of this answer (that modified Array.prototype.move) can be found on npm at array.prototype.move.
I had fairly good success with this function:
Note that the last
returnis simply for testing purposes:spliceperforms operations on the array in-place, so a return is not necessary. By extension, thismoveis an in-place operation. If you want to avoid that and return a copy, useslice.Stepping through the code:
new_indexis greater than the length of the array, we want (I presume) to pad the array properly with newundefineds. This little snippet handles this by pushingundefinedon the array until we have the proper length.arr.splice(old_index, 1)[0], we splice out the old element.splicereturns the element that was spliced out, but it’s in an array. In our above example, this was[1]. So we take the first index of that array to get the raw1there.spliceto insert this element in the new_index’s place. Since we padded the array above ifnew_index > arr.length, it will probably appear in the right place, unless they’ve done something strange like pass in a negative number.A fancier version to account for negative indices:
Which should account for things like
array_move([1, 2, 3], -1, -2)properly (move the last element to the second to last place). Result for that should be[1, 3, 2].Either way, in your original question, you would do
array_move(arr, 0, 2)foraafterc. Fordbeforeb, you would doarray_move(arr, 3, 1).