EN
JavaScript - move array element from one position to another
0
points
In this article, we would like to show you how to move an array element from one position to another in JavaScript.
Practical examples
Example 1
In this example, we create a reusable arrow function that uses splice() method to move array element from indexOld position to indexNew.
Note: When
indexNewis greater or equal toarray.lengththe remaining space will be filled withundefinedvalues (go to the Example 2).
// ONLINE-RUNNER:browser;
const moveElement = (array, indexOld, indexNew) => {
if (indexNew >= array.length) {
let n = indexNew - array.length + 1;
while (n--) {
array.push(undefined);
}
}
array.splice(indexNew, 0, array.splice(indexOld, 1)[0]);
};
// Usage example:
const array = ['a', 'b', 'c'];
moveElement(array, 0, 1); // moves element from index 0 to index 1
console.log(array); // [ 'b', 'a', 'c' ]
Example 2
In this section, we present how the moveElement() method works when indexNew is greater than array.length value.
// ONLINE-RUNNER:browser;
const moveElement = (array, indexOld, indexNew) => {
if (indexNew >= array.length) {
let n = indexNew - array.length + 1;
while (n--) {
array.push(undefined);
}
}
array.splice(indexNew, 0, array.splice(indexOld, 1)[0]);
};
// Usage example:
const array = ['a', 'b', 'c'];
moveElement(array, 0, 5); // moves element from index 0 to index 5
console.log(array); // ['b','c', , , ,'a']