0

I am trying to sum the elements inside a nested array. For example arraySum([1,[2,3],5,[[4]]]) should return 15

Everything seems ok except when I try to return array.pop() + arraySum(array) it goes into a weird infinite loop.

Everything goes well until code reaches that code. I tried to return the value of the array and I see no problems at all.

Can anyone tell me what's wrong with my code?

var arraySum = function(array) {
  
  if(array.length === 0){
      return 0
    }
  if(Array.isArray(array[array.length - 1])){
    var x = array[array.length - 1].reduce((accumulator, currentValue) => accumulator + currentValue);

    array.pop()
    array.push(x)
    return arraySum(array)

    }       

  return  array.pop() + arraySum(array)
};

console.log(arraySum([1,[2,3],5,[[4]]]))
Mulan
  • 129,518
  • 31
  • 228
  • 259
Adolf
  • 53
  • 7
  • You have `if (array.length = 0)` (which sets `array.length` to 0, deleting everything in the array and evaluating to 0) instead of `if (array.length === 0)`. `a = b` sets `a` to `b`, `a === b` checks if `a` and `b` are equal. – Ry- Aug 27 '18 at 00:18
  • Hehe sorry I fixed it... but still have the same problem :/ – Adolf Aug 27 '18 at 00:20
  • 1
    You sure you saved the changes to the right file? If you make the result visible in the snippet there with `console.log(arraySum([1,[2,3],5,[[4]]]))`, it shows 15 as expected. – Ry- Aug 27 '18 at 00:21
  • just saw it... weird... in repl.it it returns infinite loop 42 43 44 45 46 47 41 40 38 39 36 37 35 34 33 32 30 31 28 29 48 49 50 51 52 53 54 Native Browser JavaScript InternalError: too much recursion at arraySum:36:1 at arraySum:50:24 ............. – Adolf Aug 27 '18 at 00:39
  • Are you trying it with different input on repl.it? – Ry- Aug 27 '18 at 00:41
  • I just checked your code in a Repl.it and it worked. Not sure what is your context, but flatten array and summing with reduce is pretty straightfwd, check it out this question: https://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays-in-javascript – Andre Figueiredo Aug 27 '18 at 00:59
  • 1
    What is the problem? When I run the code snippet you posted, it returns `15` as expected. – divibisan Aug 27 '18 at 23:27

1 Answers1

1

Some hearty recursion solves our problem here. The issue was that you were mutating the array while iterating over it, specifically pushing items back into it. In practice you should never do this.

    function arraySum(array) {
      if (array.length === 0) {
        return 0;
      }
      return array.reduce((previous, current) => {
        if (Array.isArray(current)) {
          return previous + arraySum(current);
        }
        return previous + current;
      }, 0);
    }

    console.log(arraySum([1, [2, 3], 5, [[4]]]));
snek
  • 1,980
  • 1
  • 15
  • 29