Categories
JavaScript Answers

How to sort an array of arrays in JavaScript?

Spread the love

Sometimes, we want to sort an array of arrays in JavaScript.

In this article, we’ll look at how to sort an array of arrays in JavaScript.

How to sort an array of arrays in JavaScript?

To sort an array of arrays in JavaScript, we can use the array sort method.

For instance, we write:

const array = [
  [123, 3],
  [745, 4],
  [643, 5],
  [643, 2]
];

const sortedArray = array.sort(([a], [b]) => {
  return b - a;
});

console.log(sortedArray)

We call array.sort with a callback that destructures the first entry from each nested array.

Then we return the value to determine how it’s sorted.

We rerturned b - a, so the returned sorted array will have the first entry sorted in descending order.

As a result, sortedArray is [[745, 4], [643, 5], [643, 2], [123, 3]] .

Conclusion

To sort an array of arrays in JavaScript, we can use the array sort method.

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 *