gpt4 book ai didi

javascript - 使用reduce es2015查找最小值和最大值

转载 作者:行者123 更新时间:2023-11-28 17:59:56 27 4
gpt4 key购买 nike

如果我有这样的对象数组

[{min:5,max:10,id:1}, {min:50,max:3,id:2}, {min:1,max:40,id:3}]

如何使用reduce求最小值和最大值?我知道我可以使用通用循环和比较,但我想探索 es2015 中的reduce

最佳答案

您可以像这样使用reduce来获取数组中每个对象的最小和最大数字。

const arr = [{min:5,max:10,id:1}, {min:50,max:3,id:2}, {min:1,max:40,id:3}]

console.log(
arr.reduce((acc, x) => {
acc.min = Math.min(acc.min, x.min)
acc.max = Math.max(acc.max, x.max)
return acc
}, { min: Infinity, max: -Infinity })
)

// as Bergi suggested, we could just return a new Object literal
// from the reduction
console.log(
arr.reduce((acc, x) => ({
min: Math.min(acc.min, x.min),
max: Math.max(acc.max, x.max)
}), { min: Infinity, max: -Infinity })
)

关于javascript - 使用reduce es2015查找最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43705415/

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