简体   繁体   中英

How to sum nested arrays in JavaScript

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

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

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

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

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

Using ramda:

const sumNested = compose(sum, flatten)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM