JavaScript: Moving elements inside an array, modifying the array in place

Updated . Posted . Visible to the public.

If you want to move an element inside an array, neither JavaScript/ES6+ nor libraries like LoDash offet that natively.

Here is a simple function instead that modifies the input array in place.

function moveArrayElement(array, element, offset) {
  const index = array.indexOf(element)
  const newIndex = index + offset
  
  if (newIndex > -1 && newIndex < array.length) {
    // Remove the element from the array
    const removedElement = array.splice(index, 1)[0]

    // At "newIndex", remove 0 elements and insert the removed element
    array.splice(newIndex, 0, removedElement)
  }
}

Pass the element you want to move, and define the move offset (negative to move towards the beginning):

const list = [object1, object2, object3]
moveArrayElement(list, object2, 1)
// list => [object1, object3, object2]
moveArrayElement(list, object2, -2)
// list => [object2, object1, object3]

Note that any calls which move elements beyond the array's boundaries are ignored. It was what I needed, but you could easily adjust that.

Check the linked StackOverflow post for more information and other implementations.

Arne Hartherz
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2014-08-21 10:39)