-2
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 -

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 ?

Shameen
  • 2,656
  • 1
  • 14
  • 21
C Sharper
  • 8,284
  • 26
  • 88
  • 151
  • `.reduce()` is a method of `Array.prototype` and not available on objects. If you can call `.reduce()` without an error you don't call it on an object... The variable with the misleading name `obj` is an array of objects but not an object. Hence the title is not correct. – Andreas Jan 03 '23 at 10:39
  • Why is this tagged with `reactjs` and `jquery`? Both tags are not relevant for this question. – Andreas Jan 03 '23 at 10:39

1 Answers1

2

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)
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80