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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)