使用javascript中的多个字段进行自定义排序

时间:2018-07-10 12:40:08

标签: javascript

我有一个数组

var arr = [
    0:{region:2, saved: false, damage:-1}
    1:{region:1, saved: true, damage:2}
    2:{region:1, saved: false, damage:-1}
    3:{region:1, saved: true, damage:4}
    4:{region:2, saved: true, damage:3}
    5:{region:-1, saved: false, damage:-1}
    6:{region:3, saved: false, damage:-1}
];

我需要像先对区域(升序)那样进行排序,在未保存的同一区域内首先进行排序,然后按照降序的破坏顺序进行排序。

输出应该像这样

    arr =[0:{region:-1, saved: false, damage:-1}
 1:{region:1, saved: false, damage:-1}
 2:{region:1, saved: true, damage:4}
3:{region:1, saved: true, damage:2}
4:{region:2, saved: false, damage:-1}
5:{region:2, saved: true, damage:3}
6:{region:3, saved: false, damage:-1}];

请帮助使用JavaScript进行排序。

1 个答案:

答案 0 :(得分:0)

您可以在OR函数中使用Array.sort()条件:

var arr= [
  {region:2, saved: false, damage:-1},
  {region:1, saved: true, damage:2},
  {region:1, saved: false, damage:-1},
  {region:1, saved: true, damage:4},
  {region:2, saved: true, damage:3},
  {region:-1, saved: false, damage:-1},
  {region:3, saved: false, damage:-1}
];
arr.sort(function(a, b){
   return a.region - b.region || a.saved - b.saved || b.damage - a.damage;
});

console.log(arr);