按两个不同的条件对数组中的对象排序

Sort objects in an array by two different criteria

本文关键字:条件 数组 排序 对象 两个      更新时间:2023-09-26

我有一个像这样的数组:

     var arr = [{user: '3', cash: 2}, 
      {user: 'tim', cash: 3},
      {user: '5', cash: 2}, 
      {user: 'noah', cash: 3}]

我按收入最高者排序:

arr.sort(function (a, b) {
    return b.tS - a.tS;
});

它工作得很好,但是在我对拥有最高现金的人进行排序之后,我还想按用户字段的字母顺序对每个人进行排序。请记住,有些用户可能有数字,但类型是String(不是Number)。

我不能使用库,我希望它能尽可能快地工作。

您可以链接排序标准。

对于前一步为零的每一步都有效。如果值不等于0,则计算下一个delta或比较函数并提前返回。

这里返回的值只有两个排序组,但对于较长的链,将进行下一个比较。

var arr = [{ user: '3', cash: 2 }, { user: 'tim', cash: 3 }, { user: '5', cash: 2 }, { user: 'noah', cash: 3 }];
arr.sort(function (a, b) {
    return b.cash - a.cash || a.user.localeCompare(b.user);
});
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

要获得带索引的排序,您需要将索引存储在临时数组中,并使用map排序。

var array = [{ user: '3', cash: 2 }, { user: 'tim', cash: 3 }, { user: '5', cash: 2 }, { user: 'noah', cash: 3 }];
// temporary array holds objects with position and sort-value
var mapped = array.map(function(el, i) {
    return { index: i, cash: el.cash };
});
// sorting the mapped array containing the reduced values
mapped.sort(function(a, b) {
    return  b.cash - a.cash || a.index - b.index;
});
// container for the resulting order
var result = mapped.map(function(el){
    return array[el.index];
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }