How to find the sum of the elements of an arbitrary JavaScript array

Viewed 66

There is such an arbitrary array in which I need to find the sum of all numbers without using Array.isArray:

let arr = [[1, 2, 3, [4, 5, [6, 7]]], [8, [9, 10]]]; 

The solution should look something like this:

let arr = [[1, 2, 3, 4, 5], [6, 7, 8], [9, 10]]; 

for (let i = 0; i < arr.length; i++) { 
   for (let j = 0; j < arr[i].length; j++) { 
      console.log(arr[i][j]);
   }
}

Could you please advise me on how to achieve this?

3 Answers

You could take Array#flat and Array#reduce the array or check the instance of the given value with instanceof operator.

function getSum1(array) {
    return array.flat(Infinity).reduce((sum, value) => sum + value, 0);
}

function getSum2(array) {
    let sum = 0;
    for (const value of array) {
        sum += value instanceof Array
            ? getSum2(value)
            : value
    }
    return sum;
}

let array = [[1, 2, 3, [4, 5, [6, 7]]], [8, [9, 10]]];

console.log(getSum1(array));
console.log(getSum2(array));

you use lodash for this:

var _ = require("lodash");
var arr = [[1, 2, 3, [4, 5, [6, 7]]], [8, [9, 10]]];
flatArr = _.flattenDeep(arr);
flatArr.reduce((sum, value) => sum + value, 0);
Related