我有以下对象:

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相同。我无法理解如何综合所有因素并对其进行排序。

最佳答案

您只需要在排序函数中放入一些条件即可检查年龄或密度是否相等,如果相等,则按下一组规则进行排序(年龄->密度->长度):



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)





要对键进行排序(对值进行排序更好地显示其工作原理),只需将ab替换为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)

关于javascript - 根据给定的标准对对象键进行排名,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52321905/

10-09 20:25