Reputation:
let newton = ["1", " 2", " 3", " 4", " 5"];
let newton2 = newton.reduce(sum);
function sum(total, value) {
return (total + value);
}
document.getElementById("demo").innerHTML = newton2;
<p id="demo"></p>
So...I have used the reduce function (sum) and its not summing the elemenets in the array and displaying it in a single element, Rather its displaying the elements in the array again.
Upvotes: 0
Views: 50
Reputation: 1
You should Cast string to int and then use reduce function.
function sum(total,value){
var intVal = parseInt(value);
return(total + intVal);
}
Upvotes: 0
Reputation: 4263
It's working correctly if you use number instead of strings; let newton = [1,2,3,4,5];
Alternatively you can parse string to integer if that's what you want return(total + parseInt(value));
but then you have to initialize aggregator as integer giving it an initial value, otherwise it'll still be casted to string; newton.reduce(sum, 0)
.
Upvotes: 3