Categories
JavaScript Answers

How to Reorder Arrays with JavaScript?

Spread the love

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.

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 *