我有以下对象:
let res = {
'name': {
age: 10,
density: 33,
length: 2
},
'greet': {
age: 33,
density: 92,
length: 3
},
'gyrt': {
age: 91,
density: 2,
length: 47
},
.
.
.
}
其中有更多的键值对。我被要求按“排名”的降序返回键列表,该列表受以下约束控制:
我很困惑如何实现这一目标。我正在尝试对对象进行排序,但这无济于事。我首先尝试使用age
,然后使用density
,然后使用length
进行排序,但这显然不起作用,因为对象被一次又一次地重新排序,而忘记了先前的顺序。我该如何实现?
这是我正在尝试的:
let sortByAge = keys.sort((a, b) => Number(res[b].age) - Number(res[a].age));
let sortByDensity = keys.sort((a, b) => Number(res[b].density) - Number(res[a].density));
与length
相同。我无法理解如何综合所有因素并对其进行排序。
答案 0 :(得分:1)
您只需要在排序函数中放入一些条件即可检查年龄或密度是否相等,如果相等,则按下一组规则(年龄->密度->长度)进行排序:
let a={'name':{age:10,density:33,length:2},'greet':{age:33,density:92,length:3},'gyrt':{age:91,density:2,length:47},'foo':{age:91,density:3,length:47},'bar':{age:91,density:2,length:30},'baz':{age:10,density:2,length:47},'boo':{age:91,density:2,length:47},}
let sorted = Object.values(a);
sorted.sort((a,b) => {
if(a.age === b.age) {
if(a.density === b.density) {
//sort by length
return b.length - a.length;
}
//sort by density
return a.density - b.density;
}
//sort by age
return b.age - a.age;
});
console.log(sorted)
要对键进行排序(对值进行排序更好地显示其工作原理),只需将a
和b
替换为obj[a]
和obj[b]
let obj={'name':{age:10,density:33,length:2},'greet':{age:33,density:92,length:3},'gyrt':{age:91,density:2,length:47},'foo':{age:91,density:3,length:47},'bar':{age:91,density:2,length:30},'baz':{age:10,density:2,length:47},'boo':{age:91,density:2,length:47},}
let sorted = Object.keys(obj);
sorted.sort((a,b) => {
if(obj[a].age === obj[b].age) {
if(obj[a].density === obj[b].density) {
//sort by length
return obj[b].length - obj[a].length;
}
//sort by density
return obj[a].density - obj[b].density;
}
//sort by age
return obj[b].age - obj[a].age;
});
console.log(sorted)
答案 1 :(得分:0)
使用我介绍的here函数sortBy()
,您可以创建一种将每个属性组合在一起的排序方法,如下所示:
const res = {name:{age:10,density:33,length:2},greet:{age:33,density:92,length:3},gyrt:{age:91,density:2,length:47},foo:{age:91,density:3,length:47},bar:{age:91,density:2,length:30},baz:{age:10,density:2,length:47},boo:{age:91,density:2,length:47}}
const sortBy = fn => (a, b) => -(fn(a) < fn(b)) || +(fn(a) > fn(b))
const pick = key => ({ [key]: value }) => value
const age = sortBy(pick('age'))
const density = sortBy(pick('density'))
const length = sortBy(pick('length'))
const sortFn = (a, b) =>
-age(a[1], b[1]) ||
density(a[1], b[1]) ||
-length(a[1], b[1])
const keys = Object.entries(res).sort(sortFn).map(([key, value]) => key)
console.log(keys)