Explain Codes LogoExplain Codes Logo

Move an array element from one array position to another

javascript
array-manipulation
performance-optimization
best-practices
Nikita BarsukovbyNikita Barsukov·Jan 5, 2025
TLDR

Easily relocate an element in an array with splice(), perform element surgery:

let arrayData = ['a', 'b', 'c', 'd']; arrayData.splice(1, 0, arrayData.splice(2, 1)[0]); // Assign 'c' to index 1

The outcome: arrayData now reads ['a', 'c', 'b', 'd']. Done in a single, swift line, this conducts an in-place shuffle.

Alternate positions and filling gaps

Got negative indices or want to move beyond the known universe of current array length? Here's a function to the rescue:

function array_move(arrayData, old_index, new_index) { // Checks if new_index exists, if not, create space (but fill it with undefined, it's cheaper than matter) if (new_index >= arrayData.length) { let k = new_index - arrayData.length + 1; while (k--) { arrayData.push(undefined); } } arrayData.splice(new_index, 0, arrayData.splice(old_index, 1)[0]); return arrayData; // Why not show off the newly rearranged array? }

Thinking about performance and optimization

Working with large arrays or in performance-critical apps, time is of essence and resources are gold. Minimize index adjustments and if many moves are heating up, pre-compute distances.

Moving a multitude of elements? Keep an eye out for performance bottlenecks and leverage local variables and loops.

Taking npm's help

If your app can afford an extra guest, the array-move npm package can make life easier:

npm install array-move

Its use is child's play:

const arrayMove = require('array-move'); let arrayData = ['a', 'b', 'c', 'd']; arrayData = arrayMove(arrayData, 2, 1);

Being alert with bound checks

Before element surgery with splice, always check array bounds. Unchecked bounds not only cause runtime errors but can also make a fine mess of your data.

Use the safety checks:

if (newIndex < 0 || newIndex >= array.length) { // You've gone off the array grid, rethink newIndex! }

Keeping original array intact

When you intend to preserve the original array, use move() that creates a new array:

function move(array, from, to) { let newArray = array.slice(); // Clone so that original array remains untouched, just like in a sci-fi movie newArray.splice(to, 0, newArray.splice(from, 1)[0]); // Perform array surgery return newArray; // Return the altered clone } let initialArray = ['a', 'b', 'c', 'd']; let newArray = move(initialArray, 2, 1);

Before you get thrilled and say, "It's a miracle! The initialArray remains unchanged", I must remind you this was the expected behavior.

Reindexing after Operation Element Switch

After moving elements, remember it's about time to reindex. Balancing array index is an important element of housekeeping:

for (let i = 0; i < array.length; i++) { array[i].index = i; }

Try to make equilibrium a fundamental rule for index alignment.