0

I want to total the array using the reduce method. I would use a for loop and keep it simple, but it is for my college course.

console.log(weeklyTotal);

const totalCal = weeklyTotal.reduce((total, current) => total + current, 0);

console.log(totalCal);

Here is what shows in the Chrome dev tools console

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
ryanh
  • 5
  • 4
  • convert current to a number before adding it: `total + Number(current)`, otherwise, you'll be doing string concatenation rather than addition – Nick Parsons Dec 03 '20 at 07:22
  • @NickParsons Why do people comment their responses instead of replying normally? Also, I didn't realize that the array was all strings. Can I use parseInt instead, or is using Number the newer version? I'm not exactly familiar with Number although I have seen it before. Also, thanks. – ryanh Dec 03 '20 at 07:25
  • I commented my answer because I felt like your question was going to get closed (which it did), as this is a small mistake which is either a duplicate or a typo-like question. `parseInt(current, 10)` will also work, `Number()` is generally preferred as it will work if you have both integer strings and decimal strings, so it's more versatile – Nick Parsons Dec 03 '20 at 07:29
  • @NickParsons While using parseInt(current, 10), what does the 10 do? – ryanh Dec 03 '20 at 07:51
  • The `10` specifies the "radix" of your input string, here we specify 10, so the base10 number, if you had a base2 (aka binary) string and you wanted to convert it to an integer (eg: "101" is 5 in binary), you can use `parseInt("101", 2)`. 10 is technically not the default radix, so its usually good to supply – Nick Parsons Dec 03 '20 at 07:56

0 Answers0