DEV Community

Nathan
Nathan

Posted on • Originally published at natclark.com

Move Specific Array Item in JavaScript

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;
};
Enter fullscreen mode Exit fullscreen mode

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`];
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

As expected, Green is now between Red and Blue:

console.log(colors);
// Returns [`Red`, `Green`, `Blue`, `Yellow`]
Enter fullscreen mode Exit fullscreen mode

Pretty neat, right?

Conclusion

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

Hopefully you found it useful too!

Discussion (0)