I have this array of objects:
const data = [
{val: 40, color: 'red'},
{val: 5, color: 'green'},
{val: 55, color: 'lime'}
]
This is what I would like to obtain:
const result = [
{val: 40, color: 'red'},
{val: 45, color: 'green'},
{val: 100, color: 'lime'}
]
So each item should have the same color and the cumulative value of previous data.
This is what I try:
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)
Where is the error? Why r[i - 1] is undefined?
data[0]is incorrect. It should be[]because you want it to result into a new array. Additionally, build up this array, you need toreturn [...r, newDatum], notnewDatumreducefunction return a single value. in this case, you need to usemapfunction.