我有一个对象数组,每个对象都有name
、skill
和talent
键。看起来是这样的:
let defaultArray = [
{name='person1', skill = 6, talent = 3},
{name='person2', skill = 5, talent = 5},
{name='person3', skill = 4, talent = 6},
{name='person4', skill = 2, talent = 7},
{name='person5', skill = 1, talent = 4},
{name='person6', skill = 3, talent = 1},
{name='person7', skill = 6, talent = 2}
]
我需要对其进行排序,这样我才能根据他们的技能来定义三位最优秀的人,如下所示:
let resultArray = [
{name='person1', skill = 6, talent = 3},
{name='person7', skill = 6, talent = 2},
{name='person2', skill = 5, talent = 5},
]
正如您所看到的,如果某人的技能是相同的(比如person1
和defaultArray
中的person7
),那么人员将按talent
进行排序。
请有人帮我做一个简洁的函数,把defaultArray
作为参数,并返回resultArray
,同时考虑到skill
和talent
值可以完全随机?
发布于 2020-12-25 04:44:04
const arr = [
{name:'person1', skill : 6, talent : 3},
{name:'person2', skill : 5, talent : 5},
{name:'person3', skill : 4, talent : 6},
{name:'person4', skill : 2, talent : 7},
{name:'person5', skill : 1, talent : 4},
{name:'person6', skill : 3, talent : 1},
{name:'person7', skill : 6, talent : 2}
];
arr.sort((a, b) => (b.skill - a.skill) || (b.talent - a.talent));
console.log(arr)
.as-console-wrapper { max-height: 100% !important; top: 0; }
https://stackoverflow.com/questions/65448117
复制相似问题