1

I'm trying to create a function that sums the total of all the values in an array, even if those values are nested within nested arrays. Like this: countArray(array); --> 28 (1 + 2 + 3 + 4 + 5 + 6 + 7) I tried this recursive function, but it just concatenates.

var countArray = function(array){
      var sum=0;
      for(let i=0; i<array.length; i++){
              if(array[i].isArray){
               array[i]=countArray(array[i]);
      }
    
          sum+=array[i];
        
        }
      
      return sum;
}
Unmitigated
  • 46,070
  • 7
  • 44
  • 60
Germán
  • 65
  • 5
  • 3
    Share the array content for better understanding. – Sajeeb Ahamed Dec 18 '20 at 19:20
  • `array[i].isArray` - there isn't an `isArray` property on objects/arrays. There is [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray) – VLAZ Dec 18 '20 at 19:21
  • Does this answer your question? [Sum all integers in a multidimensional array javascript](https://stackoverflow.com/questions/33665228/sum-all-integers-in-a-multidimensional-array-javascript) – Wais Kamal Dec 18 '20 at 19:24

5 Answers5

2

Flatten the array using Array.flat(), and then sum using Array.reduce():

const countArray = array => 
  array.flat(Infinity)
    .reduce((sum, n) => sum + n, 0)

console.log(countArray([1, 2, [3, [4, 5], 6], 7]));
Ori Drori
  • 166,183
  • 27
  • 198
  • 186
1
  1. Use Array.isArray to check if an object is an array.
  2. Add the result of the recursive call to the sum each time.

var countArray = function(array) {
  var sum = 0;
  for (let i = 0; i < array.length; i++) {
    if (Array.isArray(array[i])) {
      sum += countArray(array[i]);
    } else {
      sum += array[i];
    }
  }
  return sum;
}
console.log(countArray([1, 2, [3, [4, 5], 6], 7]));

You could also use Array#reduce with a recursive function.

const countArray = array => array.reduce((acc,curr)=>
   acc + (Array.isArray(curr) ? countArray(curr) : curr), 0);
console.log(countArray([1, 2, [3, [4, 5], 6], 7]));

This problem can be simplified to finding the sum of all elements in a one-dimensional array by using Array#flat beforehand.

const countArray = array => array.flat(Infinity).reduce((acc,curr)=>acc+curr, 0);
console.log(countArray([1, 2, [3, [4, 5], 6], 7]));
Unmitigated
  • 46,070
  • 7
  • 44
  • 60
1

Beside the problem of right application of Array.isArray, you have an actual use case for taking a named function, because you call the function recursively and by uzsing just a variable, the reference of the function could go.

function countArray(array) {
    var sum = 0;
    for (const value of array) {
        sum += Array.isArray(value) ? countArray(value) : value;
    }
    return sum;
}
adiga
  • 31,610
  • 8
  • 53
  • 74
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
0

Your working example:

const arr = [1, [2, [3]]]

const countArray = function(array) {
  let sum = 0;

  for (let i = 0; i < array.length; i++) {
    if (Array.isArray(array[i])) {
      sum += countArray(array[i]);
    } else {
      sum += array[i];
    }
  }

  return sum;
}

console.log(countArray(arr));

A little bit simplified example:

const arr = [1, [2, [3]]]

const countArray = (array) => {
  let sum = 0;

  for (const el of array) {
    sum += Array.isArray(el) ? countArray(el) : el
  }

  return sum;
}

console.log(countArray(arr));

Even more simple code:

const arr = [1, [2, [3]]]

const countArray = (array) =>
  array.reduce((sum, el) =>
    Array.isArray(el) ? sum + countArray(el) : sum + el, // reduce function
    0); // sum = 0 intialization

console.log(countArray(arr));
IvanD
  • 2,398
  • 7
  • 17
0

Using ramda:

const sumNested = compose(sum, flatten)

Alex Mckay
  • 2,939
  • 13
  • 22