To reorder arrays with JavaScript, we can use destructuring syntax.
For instance, we write
const swapPositions = (array, a, b) => {
[array[a], array[b]] = [array[b], array[a]];
};
let array = [1, 2, 3, 4, 5];
swapPositions(array, 0, 1);
to define the swapPositions
function that assigns array[b]
to array[a]
and array[a]
to array[b]
with destructuring to swap the positions of the array
entries at indexes a
and b
.
Then we call it with the array
and the positions we want to swap.