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.