Move Specific Array Item in JavaScript

- 2 minutes read

Sorting and rearranging ararys in JavaScript can be a bit tedious at times, to say the least.

Often, the find() method is not sufficient, let alone sufficiently performant.

Here’s a function I’ve created for more surgical operations, which moves a single item at a specific index to another index:

const moveItem = (array, to, from) => {
    const item = array[from];
    array.splice(from, 1);
    array.splice(to, 0, item);
    return array;

Each of the four lines in this function has a specific task:

  1. Get a copy of the item that needs to be moved.

  2. Remove the original item from the array.

  3. Insert the copy at the desired index.

  4. Return the resultant array.

Here’s an example of it in action. Let’s say we want to make Green go between Red and Blue in the following array:

let colors = [`Red`, `Blue`, `Yellow`, `Green`];

We can pass the array to moveItem, along with the index of the item to move and the desired target index:

// 1 is the target index we want to insert that item at
// 3 is the index of the item we want to move
colors = moveItem(colors, 1, 3);

As expected, Green is now between Red and Blue:

// Returns [`Red`, `Green`, `Blue`, `Yellow`]

Pretty neat, right?

Link to this section Conclusion

I’ve found this approach especially useful when working with object arrays.

Hopefully you found it useful too!