我有一个数组
people = [
{ "name": "Bob Mike", "nickname": "john" , "points": 5 ) },
{ "name": "Andrea Maria", "nickname": "bob", "points": 5 )}
{ "name": "Larry Kiu", "nickname": "larry", "points": 4 ) }
];
我想按照这样排序
Andrea Maria - 5
Bob Mike - 5
Larry Kiu - 4
我没有进入排序方法,我找到了这个小代码,但它只对点进行排序,不包括名称字段中的ASC。
people.sort(dynamicSort('name')).sort(dynamicSort('points'));
function dynamicSort(property) {return function(a, b) {
return (a[property] > b[property]) ? -1 : (a[property] < b[property])? 1 : 0;
}}
编辑:谢谢Erazihel
答案 0 :(得分:3)
您可以先按点排序,然后使用localeCompare
按名称排序。
var people = [
{ "name": "Bob Mike", "nickname": "john" , "points": 5 },
{ "name": "Andrea Maria", "nickname": "bob", "points": 5},
{ "name": "Larry Kiu", "nickname": "larry", "points": 4 }
];
people.sort(function(a, b) {
return b.points - a.points || a.name.localeCompare(b.name)
})
console.log(people)
答案 1 :(得分:1)
您可以使用localeCompare
来比较两个字符串
const people = [
{ name: "Bob Mike", nickname: "john" , points: 5 },
{ name: "Andrea Maria", nickname: "bob", points: 5 },
{ name: "Larry Kiu", nickname: "larry", points: 4 }
];
people.sort(function(a, b) {
return b.points - a.points || a.name.localeCompare(b.name)
});
console.log(people.map(a => a.name + ' - ' + a.points));
答案 2 :(得分:0)
你想要的是这样的
var people = [
{ "name": "Bob Mike", "nickname": "john" , "points": 5 },
{ "name": "Andrea Maria", "nickname": "bob", "points": 5},
{ "name": "Larry Kiu", "nickname": "larry", "points": 4 }
];
people.sort(compare('name')).sort(compare('points'));
function compare(property){
return function(a, b){
return a[property] <= b[property];
}
}
console.log(people);
&#13;
compare函数返回一个可以处理指定属性的函数
答案 3 :(得分:0)
通过保持用于检查对象的单个键以进行排序的函数的想法,您可以使用带有键的数组来按顺序进行排序,并使用回调构建一个新的数组,以便使用sort。
在sort callbak中,调用函数,直到结果值与truthy值不同,后者停止迭代。
function dynamicSort(key, order) {
return function(a, b) {
return +(order === 'ASC' || -1) * +(a[key] < b[key] && -1 || a[key] > b[key]);
};
}
var people = [{ name: "Bob Mike", nickname: "john" , points: 5 }, { name: "Andrea Maria", nickname: "bob", points: 5 }, { name: "Larry Kiu", nickname: "larry", points: 4 }],
sortBy = [['points', 'DESC'], ['name', 'ASC']].map(a => dynamicSort(...a));
people.sort(function (a, b) {
var v = 0;
sortBy.some(f => v = v || f(a, b));
return v;
});
console.log(people);
.as-console-wrapper { max-height: 100% !important; top: 0; }