Saturday, January 18, 2025
HomeProgrammingHow can I sort an array of arrays in JavaScript?

How can I sort an array of arrays in JavaScript?

To sort an array of arrays in JavaScript, you can use the sort() method with a custom comparator. For example, to sort by the first element in each sub-array, use:

let arr = [[3, ‘a’], [1, ‘b’], [2, ‘c’]];
arr.sort((a, b) => a[0] – b[0]);
console.log(arr); // Outputs: [[1, ‘b’], [2, ‘c’], [3, ‘a’]]

See also  What is the use of Bool type in C Programming

You can adjust the comparator to sort by other elements in the sub-arrays. For instance, to sort by the second element, use a[1] and b[1] in the comparator function. The sort() method modifies the original array in place.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x