1

I have an issue, I have to sum the numbers in an array, and what I did works fine except in one situation :

sum([1, [2, 3, [4, 5], 6], 7, [8, 9]]) === 45

function sum(arr) {
  var arrsum = 0;
  for (var index = 0; index < arr.length; index++) {
    if (!isNaN(arr[index])) {
     arrsum += arr[index];
   }
  }
  return arrsum;
}

The result for this one is 8, do you know how to make it 45 by only changing the function? Thanks a lot.

Guillaume Marc
  • 67
  • 1
  • 10
  • in essence, all you need to do is to "flatten" your array. See [this post](https://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays-in-javascript) maybe – kyriakosSt Feb 05 '18 at 21:24

2 Answers2

2

You need to calculate the sum of the inner array when each item in the array is itself an array:

function sum(array){
  var total = 0;
  for(var i = 0; i < array.length; i++){
    var item = array[i];
    if(item.constructor == Array){ //It is an array
      total += sum(item);
    }else{
      total += item;
    }
  }
  return total;
}

var array = [1, [2, 3, [4, 5], 6], 7, [8, 9]];
var result = sum(array);
console.log(result);
Javier Gonzalez
  • 915
  • 6
  • 14
2

The key is to make your function recursive when another array is found inside the first one.

console.log(sum([1, [2, 3, [4, 5], 6], 7, [8, 9]])); // === 45

function sum(arr) { 
  var result = 0; // answer will go here
  
  // This function will do the looping over all arrays
  function loop(ary){
    arr.forEach(function(element){
      // If the item is a number...
      if(typeof element === "number"){
        result += element;  // Add it to the total
      } else if(typeof element === "object"){
        // If it's an object (Array in this case), run the function recusively
        result += sum(element);    
      }
    });  
  }
  
  loop(arr);

  return result;
}
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71