簡體   English   中英

使用 reduce 對對象數組中的值求和

[英]Use reduce to sum values in array of objects

我有這個對象數組:

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]未定義?

您從單個元素開始 reduce,該元素不是數組。

相反,您可以關閉sum和 map 新對象。

 const data = [{ val: 40, color: 'red' }, { val: 5, color: 'green' }, { val: 55, color: 'lime' }], result = data.map( (sum => ({ val, color }) => ({ val: sum += val, color })) (0) ); console.log(result);

您的代碼中有四個問題:

  • 在這一行const cumVal = i === 0? val: r[i - 1].val const cumVal = i === 0? val: r[i - 1].val你應該指定0作為默認值,而不是val
  • 在這一行const newDatum = { val: cumVal, color }您需要將val添加到cumVal
  • 作為初始值,您應該傳遞一個空數組,而不是data數組的第一個元素,因為您希望得到一個數組,而不是 object
  • 您需要在每次迭代中返回r ,而不是newDatum - 再次,您希望最后有一個數組,而不是 object

這是一個固定版本:

 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)

const result2 = data.reduce((acc, { val, color }, i) => {
    val += (i>0) ? acc[i - 1].val: 0;
    return acc.concat([{ val, color }])
}, [])

您的問題的解決方案。

問題:

  1. 初始值錯誤
  2. 返回 object

雖然我認為 Map 在這里會是一個更好的選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM