按两个不同的标准对数组中的对象进行排序

时间:2016-11-11 20:17:30

标签: javascript arrays sorting

我有一个看起来像这样的数组:

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

我不能使用库,我更喜欢它在机器方面尽可能快地工作。

1 个答案:

答案 0 :(得分:5)

您可以链接排序标准。

链接适用于前三角形为零的每一步。然后,如果值不为零,则评估下一个增量或比较函数并提前返回。

此处,返回的值只有两个排序组,但对于较长的链,则进行下一次比较。



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




要获得带索引的排序,您需要将索引存储在临时数组中并使用sorting with 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; }