EN
JavaScript - reorder array
0 points
In this article, we would like to show you how to reorder an array in JavaScript.
Quick solution:
xxxxxxxxxx
1
const array = ['a', 'b', 'c', 'd'];
2
3
const indexFrom = 0; // index to move element from ('a' element)
4
const indexTo = 2; // index to move element to
5
6
array.splice(indexTo, 0, array.splice(indexFrom, 1)[0]);
7
8
console.log(array); // [ 'b', 'c', 'a', 'd' ]
In this example, we add a moveElement()
function to Array.prototype
so we can use it on any array to move an element from indexFrom
to indexTo
position.
xxxxxxxxxx
1
var array = ['a', 'b', 'c', 'd'];
2
3
Array.prototype.moveElement = function(indexFrom, indexTo) {
4
this.splice(indexTo, 0, this.splice(indexFrom, 1)[0]);
5
};
6
7
array.moveElement(0, 2);
8
9
console.log(array); // [ 'b', 'c', 'a', 'd' ]