sort Javascript 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
?
Solution 1:
grouperArray.sort(function (a, b) {
return a.gsize - b.gsize || a.glow - b.glow;
});
shorter version
Solution 2:
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);
if(aSize == bSize)
{
return (aLow < bLow) ? -1 : (aLow > bLow) ? 1 : 0;
}
else
{
return (aSize < bSize) ? -1 : 1;
}
});
Solution 3:
grouperArray.sort((a, b) => a.gsize - b.gsize || a.glow - b.glow);
Even shorter version using arrow syntax!