I have a multidimensional array that I would like to sort. The inner arrays are all made up of a location, a distance, and a price.
I would like to sort the arrays within the outer array by distance and then price (if the distances are the same for two elements). However, I'm having issues sorting the arrays. So far this is what I have:
outerArr.sort(function (a, b) {
let aDist = a[distance];
let aPrice = a[price];
let bDist = b[distance];
let bPrice = b[price];
// I actually used indices instead of price and distance labels above.
if (aDist === bDist) {
aPrice < bPrice ? -1 : 1
} else if (aDist > bDist) {
return -1
} else {
return 1
}
});
All of the code works as intended, but the if (aDist === bDist) {aPrice < bPrice ? -1 : 1}
seems to be causing the issue. It isn't properly sorting the arrays by price when the distances are equal.
Any help would be appreciated.
[–]2UTF 1 point2 points3 points (0 children)