在JavaScript中按两个值对数组进行排序

时间:2016-12-30 15:26:01

标签: javascript arrays sorting

我喜欢对2个值进行排序,首先是最高的检票口,然后是经济

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

结果应为:

  56 - 7 - 6.51
  78 - 6 - 7.10
  22 - 3 - 2.00
  34 - 3 - 6.25
  45 - 3 - 8.00
  11 - 3 - 10.25

1 个答案:

答案 0 :(得分:1)

使用logical or (||),这有助于在两个值相同时评估第二个排序选项(差异为0,这是假值)。

&#13;
&#13;
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);
&#13;
&#13;
&#13;