
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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' ] ]
- Related Articles
- How to remove an item from JavaScript array by value?
- How to move specific item in array list to the first item in Java?
- Find first duplicate item in array in linear time JavaScript
- Sort an array to have specific items first in the array - JavaScript
- How to splice duplicate item in array JavaScript
- Get the first and last item in an array using JavaScript?
- Sort an integer array, keeping first in place in JavaScript
- Sort array by month-year JavaScript
- Sort the second array according to the elements of the first array in JavaScript
- How to sort date array in JavaScript
- Remove item from a nested array by indices in JavaScript
- Sort by index of an array in JavaScript
- Sort array by year and month JavaScript
- How to append an item into a JavaScript array?
- How to sort array according to age in JavaScript?

Advertisements