user19361752
user19361752

Reputation:

The reduce fuction sum isn't reducing the elements in an array to a single element?

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

Answers (2)

Hassan Rasouli
Hassan Rasouli

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

entio
entio

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

Related Questions