Search code examples
javascriptarraysjavascript-objectsreduce

curr is undefined in reduce on array of objects


As an input, I have an array of objects , each one of these objects has a number of properties, I would like to have an output that is also an array of objects with the same properties unchanged except for one property that I like to be changed into an accumulative value. input example :

 let input_array = [{ a:'a',b:'b',c: 1},{a:'d',b:'e',c:2},{a:'g',b:'h',c: 3}];

output example

let output_array = [{ a:'a',b:'b',c: 1},{a:'d',b:'e',c:3},{a:'g',b:'h',c: 6}];

Here 's what I tried :

let output_array = [];
input_array.reduce((acc, curr) => {
    output_array.push({
        a: curr.a,
        b: curr.b,
        c : acc.c + curr.c
    })       
},0);

I keep getting c NaN and acc undefined .


Solution

  • In this case I'd prefer to .map one array to the other, and keep a variable with the accumulated c:

    const input = [{ a:'a',b:'b',c: 1},{a:'d',b:'e',c:2},{a:'g',b:'h',c: 3}];
    
    const output = input.map(((acc) => ({ c, ...rest }) => ({ ...rest, c: acc += c }))(0));
    
    console.log(output);

    For sure your solution also works if you actually return the new accumulator from the reducer:

    const input = [{ a:'a',b:'b',c: 1},{a:'d',b:'e',c:2},{a:'g',b:'h',c: 3}];
    const output = [];
    
    input.reduce((acc, curr) => {
        acc = acc + curr.c;
        output.push({ ...curr, c: acc });
        return acc;    
    },0);
    
    console.log(output);