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;
}

3
  • 3
    Share the array content for better understanding. Commented Dec 18, 2020 at 19:20
  • array[i].isArray - there isn't an isArray property on objects/arrays. There is Array.isArray() Commented Dec 18, 2020 at 19:21
  • Does this answer your question? Sum all integers in a multidimensional array javascript Commented Dec 18, 2020 at 19:24

5 Answers 5

3

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

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

Comments

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

Comments

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;
}

Comments

0

Using ramda:

const sumNested = compose(sum, flatten)

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.