1

I like to sort the 2 values, first highest wicket and then economy

var player = [  
    {"player_id":45,"wickets":3,"economy":"8.00"},
    {"player_id":11,"wickets":3,"economy":"10.25"}, 
    {"player_id":22,"wickets":3,"economy":"2.00"},  
    {"player_id":34,"wickets":3,"economy":"6.25"},  
    {"player_id":56,"wickets":7,"economy":"6.51"},  
    {"player_id":78,"wickets":6,"economy":"7.10"}
] ;   
function SortByID(x,y) {
    return ((x.wickets == y.wickets) ? 0 : ((x.wickets < y.wickets) ? 1 : -1 ));
    return ((x.economy == y.economy) ? 0 : ((x.economy > y.economy) ? -1 : 1 ));      
}

player.sort(SortByID);

The result should be :

  56 - 7 - 6.51
  78 - 6 - 7.10
  22 - 3 - 2.00
  34 - 3 - 6.25
  45 - 3 - 8.00
  11 - 3 - 10.25
Tomalak
  • 332,285
  • 67
  • 532
  • 628
Dil Dilshan
  • 361
  • 1
  • 4
  • 17

1 Answers1

1

Use logical or (||), this would help to evaluate second sorting option when both values are same ( the difference is 0 which is falsy value).

var player = [{
  "player_id": 45,
  "wickets": 3,
  "economy": "8.00"
}, {
  "player_id": 11,
  "wickets": 3,
  "economy": "10.25"
}, {
  "player_id": 22,
  "wickets": 3,
  "economy": "2.00"
}, {
  "player_id": 34,
  "wickets": 3,
  "economy": "6.25"
}, {
  "player_id": 56,
  "wickets": 7,
  "economy": "6.51"
}, {
  "player_id": 78,
  "wickets": 6,
  "economy": "7.10"
}];

function SortByID(x, y) {
  return y.wickets - x.wickets || x.economy - y.economy;
}

player.sort(SortByID);

console.log(player);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188