-4

I have a javascript object

0:
{
  firstName: "John",
  lastName: "Doe",
  score: 50,
}

1:
{
  firstName: "Jane",
  lastName: "Doe",
  score: 22,
};
.
.
.
more...

I want to sum their scores using reduce. I know it can be done with for loop to turn that into scoreArray and reduce. Is there any efficient way to use reduce on object data so I don't need to do use for loop or create unnecessary array?

Jaydeep
  • 1,686
  • 1
  • 16
  • 29

1 Answers1

0

You can just use reduce on the array of objects:

let arr = [
  { firstName: "John", lastName: "Doe", score: 50 },
  { firstName: "Jane", lastName: "Doe", score: 22, }
];

let sum = arr.reduce((acc, obj) => acc + obj.score, 0);
console.log(sum);
Turtlefight
  • 9,420
  • 2
  • 23
  • 40