Nick
Nick

Reputation: 3845

Javascript - sum of scores in an array

Im relatively new to javascript and trying to sum all the scores in the following array:

[
  { tile: "N", score: 1 },
  { tile: "K", score: 5 },
  { tile: "Z", score: 10 },
  { tile: "X", score: 8 },
  { tile: "D", score: 2 },
  { tile: "A", score: 1 },
  { tile: "E", score: 1 }
]

I have tried using this function:

function maximumScore(tileHand) {
        return tileHand.reduce((p,c) => p.score + c.score, 0);
    }

but the result I get is NaN instead of 28. However, when I replace p.score in my function with p, I get the expected result of 28.

Why is this the case?

Upvotes: 0

Views: 845

Answers (4)

Bergur
Bergur

Reputation: 4067

p stands for previous (or accumulator/sum) and c for current. You are adding previous score with current score. You then tell the reduce function to start with 0

So it tries to sum 0.score + c.score which will give NaN.

Just do p + c.score

So the loop will be

0 + 1 = 1

1 + 5 = 6

6 + 10 = 16

Etc

Upvotes: 0

junaid malik
junaid malik

Reputation: 39

// get sum of score prop across all objects in array i.e. tileHand
var scoreTotal = tileHand.reduce(function(prev, cur) {
  return prev + cur. score;
}, 0);

console.log('Total Score:', scoreTotal);

refrence: https://gist.github.com/benwells/0111163b3cccfad0804d994c70de7aa1

Upvotes: 0

Sebastian Kaczmarek
Sebastian Kaczmarek

Reputation: 8515

The reason for that is that the callback for the .reduce() method you use takes up to 4 arguments, and the first one is an accumulator. It means that it holds the accumulated value of all of the previous results returned by the callback. In this case, it's a number, not an object. So in each iteration, you have the current sum under p argument, not an object.

From the docs:

accumulator

The accumulator accumulates callback's return values. It is the accumulated value previously returned in the last invocation of the callback—or initialValue, if it was supplied (see below).

Upvotes: 0

Yeronimo
Yeronimo

Reputation: 1749

reduce's first argument is the accumulator. So the values are added to it. So it is basically a variable.

function maximumScore(tileHand) {
    return tileHand.reduce((p,c) => p + c.score, 0);
}

That will keep adding score to p, which starts at 0

Also see mozilla.org

Upvotes: 2

Related Questions