【问题标题】:How to calculate numbers within an array of objects如何计算对象数组中的数字
【发布时间】:2019-12-23 08:59:52
【问题描述】:

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

我尝试像往常一样在数组中使用 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}] 这样的数组,我想为所有a 找到sum,并为所有b 做同样的事情。

【问题讨论】:

标签: javascript arrays reactjs object


【解决方案1】:

a ( accumulator ) 没有some 属性,它是一个原始值而不是对象,所以你只需要以a 访问,而b 表示循环中的当前元素,它是一个对象,因此您需要使用key 访问值

const arr = [{ some: 1 }, { some: 2 }, { some: 3 }]
const sumArr = arr.reduce((a, b) => a + b.some, 0)

console.log(sumArr)

【讨论】:

    【解决方案2】:

    您的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)

    【讨论】:

    • 感谢您的回答,现在我更了解它的工作原理了。 :)
    【解决方案3】:

    其他答案解释了您方法中的减速器问题。现在对于您问题的第二部分:您可以简化为一个包含数组中对象中不同键的总和的对象。换句话说,将累加器更改为对象并更改reducer-lambda。类似的东西(这里有一个jsfiddle 来玩代码):

    const raw = [{a: 1}, {a: 2}, {a: 3}, {b: 4}, {b: 5}];
    
    const calcSums = someArray => someArray
      .reduce( (sums, val) => {
        Object.keys(val)
          .forEach( v => 
              sums[`sum-${v}`] = !sums[`sum-${v}`] ? val[v] : sums[`sum-${v}`] + val[v] );
        return sums;
      }, {} );
    
    
    console.log(calcSums(raw));
    
    // the method is generic, so this works too (as long as the values are numbers)
    const raw2 = [{a: 1, b:3, c:7}, {a: 2}, {a: 3}, {b: 4}, {b: 5}, {c: 9}];
    console.log(calcSums(raw2));

    【讨论】:

    • 谢谢!解释得很好,很容易理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 2018-11-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多