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.
In this example, we create a reusable arrow function that uses splice()
method to move array element from indexOld
position to indexNew
.
Note: When
indexNew
is greater or equal toarray.length
the remaining space will be filled withundefined
values (go to the Example 2).
xxxxxxxxxx
1
const moveElement = (array, indexOld, indexNew) => {
2
if (indexNew >= array.length) {
3
let n = indexNew - array.length + 1;
4
while (n--) {
5
array.push(undefined);
6
}
7
}
8
array.splice(indexNew, 0, array.splice(indexOld, 1)[0]);
9
};
10
11
12
// Usage example:
13
14
const array = ['a', 'b', 'c'];
15
16
moveElement(array, 0, 1); // moves element from index 0 to index 1
17
18
console.log(array); // [ 'b', 'a', 'c' ]
In this section, we present how the moveElement()
method works when indexNew
is greater than array.length
value.
xxxxxxxxxx
1
const moveElement = (array, indexOld, indexNew) => {
2
if (indexNew >= array.length) {
3
let n = indexNew - array.length + 1;
4
while (n--) {
5
array.push(undefined);
6
}
7
}
8
array.splice(indexNew, 0, array.splice(indexOld, 1)[0]);
9
};
10
11
12
// Usage example:
13
14
const array = ['a', 'b', 'c'];
15
16
moveElement(array, 0, 5); // moves element from index 0 to index 5
17
18
console.log(array); // ['b','c', , , ,'a']