Read more

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

Arne Hartherz
August 21, 2014Software engineer at makandra GmbH

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

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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.

Posted by Arne Hartherz to makandra dev (2014-08-21 12:39)