Categories
JavaScript Answers

How to reorder arrays with JavaScript?

Spread the love

Sometimes, we want to reorder arrays with JavaScript.

In this article, we’ll look at how to reorder arrays with JavaScript.

How to reorder arrays with JavaScript?

To reorder arrays with JavaScript, we can use array destructuring syntax.

For instance, we 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);

to create the swapPositions function that takes the array and the indexes a and b that we want to swap.

In it, we put array[b] and array[a] into an array.

And then we swap them by destructuring them on the left side.

Then we call swapPositions with the array and the indexes to swap.

array is [2, 1, 3, 4, 5] after we call swapPositions.

Conclusion

To reorder arrays with JavaScript, we can use array destructuring syntax.

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 *