Categories
JavaScript Answers

How to reorder arrays with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *