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]]]))

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. Commented Aug 27, 2018 at 0:18
  • Hehe sorry I fixed it... but still have the same problem :/ Commented Aug 27, 2018 at 0: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. Commented Aug 27, 2018 at 0: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 ............. Commented Aug 27, 2018 at 0:39
  • 1
    What is the problem? When I run the code snippet you posted, it returns 15 as expected. Commented Aug 27, 2018 at 23:27

1 Answer 1

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]]]));

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer! Very educational and informative :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.