curr is undefined in reduce on array of objects Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of curr is undefined in reduce on array of objects without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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 .

Answer

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);
We are here to answer your question about curr is undefined in reduce on array of objects - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji