use*_*653 3 javascript arrays sorting
我有一个看起来像这样的数组:
var arr = [{user: '3', cash: 2},
{user: 'tim', cash: 3},
{user: '5', cash: 2},
{user: 'noah', cash: 3}]
Run Code Online (Sandbox Code Playgroud)
我按照这样的顶级收入者排序:
arr.sort(function (a, b) {
return b.tS - a.tS;
});
Run Code Online (Sandbox Code Playgroud)
它工作正常,但在我用最高现金分类后,我想按用户字段按字母顺序排序每个人.请记住,某些用户可能有数字但类型为String(不是Number).
我不能使用库,我更喜欢它在机器方面尽可能快地工作.
您可以链接排序标准.
链接适用于前三角形为零的每一步.然后,如果该值不为零,则评估下一个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);Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
要获得带索引的排序,您需要将索引存储在临时数组中并使用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);Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
90 次 |
| 最近记录: |