Question: 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

```js
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?

Answer: 
Firstly you need to do single for incoming nested array.   
 You can use [flat()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) method.

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

```

[Array.prototype.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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,

```js
    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))
```
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:

```js
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](https://www.techiedelight.com/recursively-flatten-nested-array-javascript/)