Sometimes, we want to reorder arrays with JavaScript.
In this article, we’ll look at how to reorder arrays with JavaScript.
Reorder Arrays with JavaScript
We can reorder arrays with JavaScript with destructuring.
For instance, we can write:
const swapPositions = (array, a, b) => {
[array[a], array[b]] = [array[b], array[a]]
}
const array = [1, 2, 3, 4, 5];
swapPositions(array, 0, 1);
console.log(array)
We create the swapPositions
array with the array
to reorder, and the a
and b
parameters which are the indexes of array items to swap.
In the function body, we swap the position of the elements with indexes a
and b
by putting them both in an array and then destructuring them.
This will swap the 2 array
items in place.
Therefore, when we call swapPositions
with array
, 0, and 1, we get:
[2, 1, 3, 4, 5]
as a result.
Conclusion
We can reorder arrays with JavaScript with destructuring.