How to Move an Array Element from One Index to Another in JavaScript
Reordering elements within an array is a common requirement for tasks like building a drag-and-drop interface, managing a priority queue, or simply re-arranging data. While JavaScript has no direct move() method, this functionality can be easily achieved by combining two operations with the versatile Array.prototype.splice() method.
This guide will teach you how to create a reusable function to move an array element from a starting index to a new index. We will cover both the mutating approach that modifies the original array and the non-mutating (immutable) approach that creates a new, reordered array.
The Core Method: A Two-Step splice()
The logic for moving an element is a simple, two-step "cut and paste" operation:
- Cut: Remove the element from its original position (
fromIndex), which returns an array containing just that element. - Paste: Insert that same element at the new position (
toIndex).
The Array.prototype.splice() method is perfect for both of these actions.
How the splice() Method Works for Moving
The splice() method can add, remove, or replace elements in an array. Its syntax is:
array.splice(startIndex, deleteCount, item1, item2, ...)
- To Remove an Element: We call
splicewith adeleteCountof1. This method returns an array of the removed elements.const arr = ['a', 'b', 'c'];
const removed = arr.splice(0, 1); // Remove 1 element at index 0
console.log(removed); // Output: ['a']
console.log(arr); // Output: ['b', 'c'] - To Insert an Element: We call
splicewith adeleteCountof0.const arr = ['b', 'c'];
arr.splice(1, 0, 'a'); // At index 1, delete 0 elements, and insert 'a'
console.log(arr); // Output: ['b', 'a', 'c']
By combining these two uses, we can effectively move an element!
The Mutating Approach (Modifying the Original Array)
This approach directly modifies the array it is given. This is efficient but can lead to unexpected side effects if other parts of your code rely on the original, unmodified array.
For example, you have an array and you want to move the first element to the end.
// Problem: Move 'apple' from index 0 to index 2.
const fruits = ['apple', 'banana', 'cherry'];
Solution: this function encapsulates the two-step splice logic.
function moveElement(array, fromIndex, toIndex) {
// 1. "Cut" the element from the array
const element = array.splice(fromIndex, 1)[0];
// 2. "Paste" the element at the new index
array.splice(toIndex, 0, element);
}
// Example Usage:
const fruits = ['apple', 'banana', 'cherry'];
moveElement(fruits, 0, 2);
console.log(fruits); // Output: ['banana', 'cherry', 'apple']
// The original `fruits` array has been modified.
The Non-Mutating Approach (Creating a New Array) (Recommended)
In modern JavaScript, especially in functional programming and frameworks like React, it is often a best practice to treat data as immutable. This means you create a new array with the changes instead of modifying the original one.
Solution: to do this, we first create a shallow copy of the input array and then perform the splice operations on the copy.
function moveElementImmutable(array, fromIndex, toIndex) {
// 1. Create a shallow copy of the array
const newArray = [...array];
// 2. "Cut" the element from the new array
const element = newArray.splice(fromIndex, 1)[0];
// 3. "Paste" the element into the new array
newArray.splice(toIndex, 0, element);
// 4. Return the new array
return newArray;
}
// Example Usage:
const originalFruits = ['apple', 'banana', 'cherry'];
const newFruits = moveElementImmutable(originalFruits, 0, 2);
console.log(newFruits); // Output: ['banana', 'cherry', 'apple']
console.log(originalFruits); // Output: ['apple', 'banana', 'cherry'] (Unchanged)
This is the recommended best practice because it is safer and more predictable, as it does not cause side effects.
Conclusion
Moving an element in a JavaScript array is a common task that can be accomplished with a combination of splice() operations.
- The core logic is to
spliceout the element from its original position and thenspliceit back in at the new position. - The non-mutating (immutable) approach is the recommended best practice. It involves creating a copy of the array (e.g., with spread syntax
[...array]) before performing the move, which prevents side effects. - The mutating approach is more memory-efficient as it modifies the array in place, but should be used with caution.
By creating a reusable function like moveElementImmutable, you can write clean, predictable, and safe code for reordering array elements.