gpt4 book ai didi

javascript - ES6 使用reduce 查找组合的多个值的最大值

转载 作者:行者123 更新时间:2023-11-28 13:03:16 24 4
gpt4 key购买 nike

我有以下方法可以找到信用最高的用户

let highest = this.users.reduce((max, current) => {
current.credits > max.credits ? current : max, {credits: 0}
});

Now I'm wondering how I can see who has the highest (credits + shots)

我尝试了以下操作但没有成功,我变得未定义

let bestSupporter = this.users.reduce((max, current) => {
(current.credits + current.shots) > (max.credits + max.shots) ? current : max, {credits: 0}
});

以下方法也不起作用(将镜头添加到初始值

let bestSupporter = this.users.reduce((max, current) => {
(current.credits + current.shots) > (max.credits + max.shots) ? current : max, {credits: 0, shots: 0}
});

最佳答案

在箭头函数中使用大括号,您需要一个 return 语句。

然后,您可以使用起始值来检查该值

let highest = this.users.reduce((max, current) => {
return current.credits > max.credits ? current : max,
}, { credits: 0 });

或者省略起始值并直接使用对象。

let highest = this.users.reduce((a, b) => a.credits > b.credits ? a : b);

关于javascript - ES6 使用reduce 查找组合的多个值的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48793792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com