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 money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
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)