0

I am currently sorting a list of data by "ranking" from Highest to lowest. I would like to add a second sort to sort by mileage that is closest (ascending order). That value would be a.Distance

For example I would like it to be sorted like so

Ranking 8 Distance 1
Ranking 8 Distance 3
Ranking 7 Distance 3
Ranking 7 Distance 6
Ranking 5 Distance 2
Ranking 5 Distance 8

 //Sort by rating
            result.sort(function (a, b) {
                if (b.Ranking > a.Ranking) {
                    return 1;
                }
                if (b.Ranking < a.Ranking) {
                    return -1;
                }
                return 0; // a must be equal to b
            });
Steve Wolfe
  • 71
  • 1
  • 1
  • 10

1 Answers1

2

A "second" sort condition only holds any meaning for groups of elements where the first sort condition resulted in an answer of 0, meaning their relative order doesn't matter.

This means you can and should implement this in the same sort function you already have. The second sort condition simply only comes into play when the first one would reach no conclusion.

let result = [
  { Ranking: 5, Distance: 8 },
  { Ranking: 8, Distance: 3 },
  { Ranking: 5, Distance: 2 },
  { Ranking: 7, Distance: 6 },
  { Ranking: 8, Distance: 1 },
  { Ranking: 7, Distance: 3 }
];

let output = result.sort(function(a, b) {
  if (a.Ranking == b.Ranking) return a.Distance - b.Distance;
  return b.Ranking - a.Ranking;
});

console.log(output);
Klaycon
  • 10,599
  • 18
  • 35
  • Brilliant o(n) solution. FWIF this solution could be altered easily to adjust for n-sorting conditions. This should be the accepted answer. – jrnxf Apr 24 '20 at 19:12