1

I have to create a function that receives an array in which every element is a number, or it can be another array with numbers inside, for example : const array = [1, [2, [3,4]], [5,6], 7]; The function should count all the values and return it countArray(array); --> should return 28 because (1 + 2 + 3 + 4 + 5 + 6 + 7)

I tried this

const array = [1, [2, [3,4]], [5,6], 7];

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

console.log(countArray(array));

but this does not work, anybody knows why?

Andy
  • 61,948
  • 13
  • 68
  • 95
Fernando
  • 11
  • 1
  • You're calling `countArray`, but you aren't using the result – Michael Horn May 26 '22 at 16:42
  • You might want to just [`Array.flat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) first, then [sum normally](https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers). – Wyck May 26 '22 at 16:44
  • You add `array[i]` to `sum` whether it is itself an array or not. – Scott Hunter May 26 '22 at 16:45

5 Answers5

5

Firstly you need to do single for incoming nested array.
You can use flat() method.

var nestedArray = [0, 1, 2, [3, 4]]; 
var flatArray = nestedArray.flat(Infinity); // [0,1,2,3,4];

Array.prototype.reduce can be used to iterate through the array,
adding the current element value to the sum of the previous element values

var totalSum = flatArray.reduce(function (accumulator, a) {
  return accumulator + a;
}, 0)

So,

    const array = [1, [2, [3,4]], [5,6], 7];
    
    var countArray = function(array) {
    
      var flatArray = array.flat(Infinity);
      var totalSum = flatArray.reduce(function (accumulator, a) {
        return accumulator + a;
      }, 0)
    
      return totalSum;
    }
    
    console.log(countArray(array))
Tibrogargan
  • 4,508
  • 3
  • 19
  • 38
2

Two solutions. First is simply to modify these lines:

        if (Array.isArray(array[i])) {
            countArray(array[i])
        }
        sum= sum + array[i]

to these:

        if (Array.isArray(array[i])) {
            sum += countArray(array[i])
        } else {
            sum += array[i]
        }

or this:

        sum += Array.isArray(array[i]) ? countArray(array[i]) : array[i]

Second solution:

const array = [1, [2, [3,4]], [5,6], 7]

countArray = array => array.flat(Infinity).reduce( (a, c) => a + c, 0 );

console.log(countArray(array))

The second solution depends on Array.prototype.flat, which is fairly (ECMA 2019) recent so support may not be 100%. There are other options, pretty good list here

Tibrogargan
  • 4,508
  • 3
  • 19
  • 38
2

To spare you the effort of recursion here's a simple trick.

Ordinarily, on its own, flat will only flatten a series of nested arrays one level deep. If you supply Infinity as an argument you can flatten nested arrays n-level deep, and then you can reduce over those elements to get the sum.

const array = [1, [2, [3,4]], [5,6, [3, [23, [1, 2, [12]]]]], 7];

function countArray(arr) {
  return arr
    .flat(Infinity)
    .reduce((acc, c) => acc + c, 0);
}

console.log(countArray(array));
Andy
  • 61,948
  • 13
  • 68
  • 95
1

you can use flat(infinity) to have all the numbers in the array and then loop through each one to sum them up.

const array = [1, [2, [3, 4]], [5, 6], 7];

const fixedArray = array.flat(Infinity);

let sum = 0;
for (let index = 0; index < fixedArray.length; index++) {
  sum += fixedArray[index];
}

console.log("sum: ", sum);
0

Changing as little as possible about your code, you need add either the countArray of the item (if the item is an array) or the item itself (if it's not an array) to the sum.

const array = [1, [2, [3,4]], [5,6], 7];

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

console.log(countArray(array));
Wyck
  • 10,311
  • 6
  • 39
  • 60