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


Let’s say we have the following array −

var studentDetails =
[
   [89, "John"],
   [78, "John"],
   [94, "John"],
   [47, "John"],
   [33, "John"]
];

And we need to sort the array on the basis of the first item i.e. 89, 78, 94, etc. For this, use sort().

Example

Following is the code −

var studentDetails =
   [
      [89, "John"],
      [78, "John"],
      [94, "John"],
      [47, "John"],
      [33, "John"]
   ];
studentDetails.sort((first, second) => second[0] - first[0])
console.log(studentDetails);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo293.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo293.js
[
   [ 94, 'John' ],
   [ 89, 'John' ],
   [ 78, 'John' ],
   [ 47, 'John' ],
   [ 33, 'John' ]
]

Updated on: 09-Nov-2020

341 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements