- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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' ] ]
Advertisements