javascript - 使用 reduce 对对象数组中的值求和

标签 javascript reduce cumulative-sum

我有这个对象数组:

const data = [
  {val: 40, color: 'red'},
  {val: 5, color: 'green'},
  {val: 55, color: 'lime'}
]

这是我想要得到的:

const result = [
  {val: 40, color: 'red'},
  {val: 45, color: 'green'},
  {val: 100, color: 'lime'}
]

所以每一项都应该有相同的颜色和之前数据的累积值。

这是我的尝试:

const data = [
  {val: 40, color: 'red'},
  {val: 5, color: 'green'},
  {val: 55, color: 'lime'}
]

// const result = [
//   {val: 40, color: 'red'},
//   {val: 45, color: 'green'},
//   {val: 100, color: 'lime'}
// ]

const result = data.reduce((r, value, i) => {
    const { val, color } = value
    const cumVal = i === 0 ? val : r[i - 1].val
    const newDatum = { val: cumVal, color }
    return newDatum
}, data[0])

console.log(result)

错在哪里?为什么 r[i - 1] 未定义?

最佳答案

您的代码中有四个问题:

  • 在这一行 const cumVal = i === 0 ? val : r[i - 1].val 你应该指定 0 作为默认值,而不是 val
  • 在这一行 const newDatum = { val: cumVal, color } 中,您需要将 val 添加到 cumVal
  • 作为初始值,您应该传递一个空数组,而不是您的 data 数组的第一个元素,因为您希望得到一个数组作为结果,而不是一个对象
  • 您需要在每次迭代中返回 r,而不是 newDatum - 同样,您希望最后有一个数组,而不是一个对象

这是一个固定版本:

const data = [
  {val: 40, color: 'red'},
  {val: 5, color: 'green'},
  {val: 55, color: 'lime'}
]

// const result = [
//   {val: 40, color: 'red'},
//   {val: 45, color: 'green'},
//   {val: 100, color: 'lime'}
// ]

const result = data.reduce((r, value, i) => {
    const { val, color } = value
    const cumVal = i === 0 ? 0 : r[i - 1].val
    const newDatum = { val: val + cumVal, color }
    r.push(newDatum);
    return r;
}, [])

console.log(result)

关于javascript - 使用 reduce 对对象数组中的值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62897814/

相关文章:

javascript - 元素插入不会立即显示在 chrome 中

python - 使用 pandas 获取列的当前最大值并输入到新列中

sql - 如何将每行 SUM() 转换为另一列

javascript - 创建 cookie 将不起作用

javascript - 如何使用(仅)Javascript 将 HTML Canvas 保存为命名的 .PNG

javascript canvas touchstart 和 touchend 不能在触摸屏上工作

javascript reduce 未定义

python - 在python中按键减少

python-3.x - Python - PyDash 使用累加器进行减少的示例

python - 在 Python 中向量化包含 cumsum() 和迭代切片的 for 循环