1

I am trying to sum the contents of an array like these:

var cardsBen = [10,2]

var cardsAmy = [4,10]

When I use a for loop, it works.

for(var i = 0; i < cardsBen.length; i++){
  cardsBen[i] = Number(cardsBen[i]);
}

When I use forEach, it doesn't convert.

cardsAmy.forEach(function(item)
  {
    Number(item);
  });

I know this because, when I then reduce the arrays, I get 12 for Ben and 410 for Amy.

var sumBen = cardsBen.reduce(function(sum, nbr){return sum + nbr});
var sumAmy = cardsAmy.reduce(function(sum, nbr){return sum + nbr});
4
  • please add the wanted result as well. Commented Dec 1, 2017 at 21:23
  • What exactly do you think happens to the result of Number(item)? Commented Dec 1, 2017 at 21:24
  • you still have numbers, no Number required. Commented Dec 1, 2017 at 21:24
  • you can use +sum + +nbr Commented Dec 1, 2017 at 21:25

2 Answers 2

7

Primitive values can't be mutated. So when doing Number(item) you have to assign that back to the array like:

cardsAmy.forEach(function(item, i) {
    cardsAmy[i] = Number(item);
});

And you can do that directly in reduce (without needing the above forEach code) like:

var sumBen = cardsBen.reduce(function(sum, nbr) { return sum + Number(nbr); }, 0);
//                                                             ^^^^^^^   ^
Sign up to request clarification or add additional context in comments.

5 Comments

Yes - That's it. Thanks. Can't click the check mark for 3 minutes.
Best response would include an initial value to reduce. Try again with var cardsBen = [] and see,,,
@RaphaMex Good point! Added an initial value. Although I don't think it will be necessary (in this case).
At this point, I am just trying to learn how to use all the array methods instead of always using a for loop. I have searched for array katas on CodeWars to try to get some practice. I think a "next step" would be to learn to combine/string methods together. But, first things first.
@Janet Combining/chaining them will come natural once you understand them well. Good luck!
2

You could use reduce with an implicit casting to number with an unary plus +.

sum = array.reduce(function (s, v) {
    return s + +v;
}, 0);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.