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
0

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.