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
Solution 1:
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]));
Solution 2:
- Use
Array.isArray
to check if an object is an array. - 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]));
Solution 3:
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;
}
Solution 4:
Using ramda:
const sumNested = compose(sum, flatten)
Solution 5:
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));
Post a Comment for "How To Sum Nested Arrays In JavaScript"