How to sort array by first item in subarray - JavaScript?

In JavaScript, you can sort an array of subarrays based on the first element of each subarray using the sort() method with a custom comparison function.

The Problem

Consider an array where each element is itself an array, and you want to sort by the first item in each subarray:

var studentDetails = [
    [89, "John"],
    [78, "Mary"],
    [94, "Alice"],
    [47, "Bob"],
    [33, "Carol"]
];

Sorting in Descending Order

To sort by the first element in descending order (highest to lowest), use a comparison function that subtracts the first element of the first subarray from the first element of the second:

var studentDetails = [
    [89, "John"],
    [78, "Mary"],
    [94, "Alice"],
    [47, "Bob"],
    [33, "Carol"]
];

studentDetails.sort((first, second) => second[0] - first[0]);
console.log(studentDetails);
[
  [ 94, 'Alice' ],
  [ 89, 'John' ],
  [ 78, 'Mary' ],
  [ 47, 'Bob' ],
  [ 33, 'Carol' ]
]

Sorting in Ascending Order

To sort in ascending order (lowest to highest), reverse the subtraction:

var studentDetails = [
    [89, "John"],
    [78, "Mary"],
    [94, "Alice"],
    [47, "Bob"],
    [33, "Carol"]
];

studentDetails.sort((first, second) => first[0] - second[0]);
console.log(studentDetails);
[
  [ 33, 'Carol' ],
  [ 47, 'Bob' ],
  [ 78, 'Mary' ],
  [ 89, 'John' ],
  [ 94, 'Alice' ]
]

How It Works

The sort() method accepts a comparison function that receives two elements to compare. The function should return:

  • A negative value if the first element should come before the second
  • A positive value if the first element should come after the second
  • Zero if they are equal

By accessing element[0], we compare the first item of each subarray.

Conclusion

Use array.sort((a, b) => b[0] - a[0]) for descending order or array.sort((a, b) => a[0] - b[0]) for ascending order when sorting by the first element of subarrays.

Updated on: 2026-03-15T23:19:00+05:30

583 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements