0

This is probably basic, but I don't understand how javascript is processing this.

I have a mixed array of numbers and numbers in string form. The following formula doesn't work when the lead item is in string form. The reduce method ends up returning a concatenated string instead of a sum.


function sumMix(x) {
  return x.reduce((acc, value) => acc + Number(value));
}

sumMix(['5', '0', 9, 3, 2, 1, '9', 6, 7])

Why isn't Number() successfully converting the item to number format when its the first item in the array? Why does it work fine so long as the first item is already a number type?

Its not a problem creating a solution in another way, but I don't understand why reduce won't work in this case.

bruzky
  • 76
  • 4
  • 3
    Pass the initial value as zero: `x.reduce((acc, value) => acc + Number(value), 0)` – VLAZ Jul 05 '21 at 20:21
  • (If you don't give `.reduce` an initial value, it uses the first item in the array instead and begins iteration at the second.) – shabs Jul 05 '21 at 20:25
  • 1
    You could also do `Number(acc) + Number(value)` – Barmar Jul 05 '21 at 20:26
  • @Barmar or `x.map(Number).reduce((acc, value) => acc + value))`. But I think starting with a neutral element for the operation is the easiest. – VLAZ Jul 05 '21 at 20:28

0 Answers0