gpt4 book ai didi

javascript - 如何计算对象数组中的数字

转载 作者:行者123 更新时间:2023-11-28 17:00:52 25 4
gpt4 key购买 nike

我有一个 obj 数组,其中有一些 NumPy ,我想找到总和。我知道如何用一个简单的数组来实现这一点,但在这种情况下它看起来很困惑。

我尝试像通常在数组中那样使用reduce,但它不起作用。

    const arr = [{ some: 1 }, { some: 2 }, { some: 3 }]

const sumArr = arr.reduce((a, b) => a.some + b.some, 0)

console.log(sumArr)

例如,我知道我可以这样做:

    const arr = [1, 2, 3, 4, 5]

const sumArr = arr.reduce((a, b) => a + b, 0)

console.log(sumArr)

如果我有一个像 [{a: 1}, {a: 2}, {a: 3}, {b: 4}, {b: 5}] 这样的数组 我想要查找所有 asum,并对所有 b 执行相同操作。

最佳答案

你的a累加器。它以 0 开始,听起来您希望它在每次迭代中都变成一个数字,以便最终整个 reduce 解析为一个数字。

使用(a, b) => a + b.some代替:

const arr = [{ some: 1 }, { some: 2 }, { some: 3 }]

const sumArr = arr.reduce((a, b) => a + b.some, 0)

console.log(sumArr)

关于javascript - 如何计算对象数组中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57534742/

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