Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript sort array by two numeric fields

grouperArray.sort(function (a, b) {     var aSize = a.gsize;     var bSize = b.gsize;     var aLow = a.glow;     var bLow = b.glow;     console.log(aLow + " | " + bLow);           return (aSize < bSize) ? -1 : (aSize > bSize) ? 1 : 0; }); 

This code sorts the array by gsize, smallest to largest.

How would I change it to sort first by gsize and then by glow?

like image 387
Mark Avatar asked May 25 '11 19:05

Mark


People also ask

How do you sort an array with two elements?

Step 1 : Here we can take two pointers type0 (for element 0) starting from beginning (index = 0) and type1 (for element 1) starting from end index. Step 2: We intend to put 1 to the right side of the array. Once we have done this then 0 will definitely towards left side of array to achieve this we do following.

How do you sort an array in numerical order?

We can use . sort((a,b)=>a-b) to sort an array of numbers in ascending numerical order or . sort((a,b)=>b-a) for descending order.


1 Answers

grouperArray.sort(function (a, b) {        return a.gsize - b.gsize || a.glow - b.glow; }); 

shorter version

like image 69
anmorozov23 Avatar answered Sep 23 '22 13:09

anmorozov23