-2

So I'm learning about the reduce method and I write this code...

function getSum(x,y){
  return x+y
  }
var arraySum = function(array) {
  return array.reduce(getSum)
};

arraySum([1,[2,3],[[4]],5])

But it actually returns a string of the elements all-together...

I'm actually trying to sum them all... I expected the result to be 15 instead of "12,345"

What's happening? what am I doing wrong?

Adolf
  • 53
  • 7
  • Out of curiosity what result did you expect to get? – David Thomas Aug 26 '18 at 03:38
  • 1
    You're performing `int + array`. The only way JS knows how to combine these is as strings. For example, `1 + [2]` results in `"12"`. Similarly, `1 + [2,3]` will combine `1 and "2,3"` for a result of `"1,23"`. – Tyler Roper Aug 26 '18 at 03:38

1 Answers1

0

Your problem is you're adding actual arrays together, not the content within the arrays. Add a counter, and an incrementational variable like i inside the variable arraySum, and call the position of i, incrementing it every time, it should fix your problem.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79