Janet
Janet

Reputation: 45

How do I convert strings in an array to numbers using forEach?

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});

Upvotes: 1

Views: 998

Answers (2)

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

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);
//                                                             ^^^^^^^   ^

Upvotes: 7

Nina Scholz
Nina Scholz

Reputation: 386560

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

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

Upvotes: 2

Related Questions