-2

say that I have:

var arr = ['-1254', '+2343']

I want my sum to be 1,089

I tried parseInt(arr.reduce((a, b) => a + b, 0)) but it returns 0.

How can find the sum of arr?

mousetail
  • 7,009
  • 4
  • 25
  • 45
  • Does this answer your question? [How to find the sum of an array of numbers](https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers) – Jorge Guerreiro Sep 01 '22 at 08:03
  • 3
    You need to convert the strings to numbers first. Try `arr.map(Number).reduce ...` – evolutionxbox Sep 01 '22 at 08:03
  • Use `parseInt` first then reduce later. You are trying to parse the array which is invalid – mousetail Sep 01 '22 at 08:04
  • duplicate [How to sum an array of strings, representing ints](https://stackoverflow.com/questions/13128610/how-to-sum-an-array-of-strings-representing-ints) – pilchard Sep 01 '22 at 08:07
  • @JorgeGuerreiro, thanks for your answer, unfortunately it doesn't because I have an array of strings. so the sum would turn out to be '0-1254+2343' –  Sep 01 '22 at 08:07
  • And since you already know the issue based on your last comment: [Adding two numbers concatenates them instead of calculating the sum](https://stackoverflow.com/questions/14496531/adding-two-numbers-concatenates-them-instead-of-calculating-the-sum) – pilchard Sep 01 '22 at 08:10

2 Answers2

1

You got 0 because in arr.reduce() initial a value is 0 number type. but b is current value that is '-1245' is string. So that's why it's not calculate.

If you want to calculate it properly you need to make b as an integer. Like this.

var result = arr.reduce((a, b) => a + parseInt(b), 0)

then log this. Thank you

-1

you need to convert string into number first.

var arr = ['-1254', '+2343']

arr.reduce((a, b) => a *1 + b * 1,0)
Himanshu
  • 919
  • 5
  • 12