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?
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?
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
you need to convert string into number first.
var arr = ['-1254', '+2343']
arr.reduce((a, b) => a *1 + b * 1,0)