Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Reduce for object

const obj=[{
name: "john",
marks: 50
},
{
name: "mary",
marks: 55
},
{
name: "peter",
marks: 75
}
];

I want to calculate sum of marks using reduce method.

I tried through this way –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const sum = obj.reduce((next, number) => {
  console.log('next',next.marks);
  console.log('number',number.marks);
  return next.marks+ number.marks;
});    

console.log(sum);

But I am getting sum as NaN and overall result as –

next 50
number 55
next undefined
number 75
NaN

I am not sure why next is getting undefined in between.

How can I calculate sum through reduce method ?

>Solution :

Pass a default value to reduce as 0

const obj=[{ name: "john", marks: 50 }, { name: "mary", marks: 55 }, { name: "peter", marks: 75 } ];


const sum = obj.reduce((acc, number) => {
  return acc+ number.marks;
}, 0);

console.log(sum)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading