3 回答
![?](http://img1.sycdn.imooc.com/54584cd10001404b02200220-100-100.jpg)
TA贡献1828条经验 获得超6个赞
使用 Object.entries 进行简单的 reduce
const items = [
{ Strength: 5 },
{ Dexterity: 6 },
{ Constitution: 3 },
{ Wisdom: 4 },
{ Charisma: 8 }
]
const biggest = items.reduce((biggest, current, ind) => {
const parts = Object.entries(current)[0] //RETURNS [KEY, VALUE]
return (!ind || parts[1] > biggest[1]) ? parts : biggest // IF FIRST OR BIGGER
}, null)
console.log(biggest[0]) // 0 = KEY, 1 = BIGGEST VALUE
您的数据模型对于带有对象的数组有点奇怪,更好的模型只是一个对象。
const items = {
Strength: 5,
Dexterity: 6,
Constitution: 3,
Wisdom: 4,
Charisma: 8
}
const biggest = Object.entries(items)
.reduce((biggest, current, ind) => {
const parts = current
return (!ind || parts[1] > biggest[1]) ? parts : biggest
}, null)
console.log(biggest[0])
![?](http://img1.sycdn.imooc.com/54584f850001c0bc02200220-100-100.jpg)
TA贡献1802条经验 获得超5个赞
您可以创建一个对象,获取条目并通过获取具有最大值的条目来减少条目。最后从入口拿钥匙。
var data = [{ Strength: 5 }, { Dexterity: 6 }, { Constitution: 3 }, { Wisdom: 4 }, { Charisma: 8 }],
greatest = Object
.entries(Object.assign({}, ...data))
.reduce((a, b) => a[1] > b[1] ? a : b)
[0];
console.log(greatest);
![?](http://img1.sycdn.imooc.com/5333a0aa000121d702000200-100-100.jpg)
TA贡献1796条经验 获得超4个赞
按降序排序并获取第一项:
let attributes = [
{Strength: 5},
{Dexterity: 6},
{Constitution: 3},
{Wisdom: 4},
{Charisma: 8}
];
//for convenience
const getValue = obj => Object.values(obj)[0];
//sort descending
attributes.sort((a, b) => getValue(b) - getValue(a));
let highest = attributes[0];
console.log(Object.keys(highest)[0]);
或者,遍历数组并找到最高分:
let attributes = [
{Strength: 5},
{Dexterity: 6},
{Constitution: 3},
{Wisdom: 4},
{Charisma: 8}
];
//for convenience
const getValue = obj => Object.values(obj)[0];
//find the highest score
let highest = attributes.reduce((currentHighest, nextItem) => getValue(currentHighest) > getValue(nextItem) ? currentHighest : nextItem);
console.log(Object.keys(highest)[0]);
添加回答
举报