A
A
Antonio092020-05-10 15:57:54
JavaScript
Antonio09, 2020-05-10 15:57:54

How to find the sum of subarrays of a multidimensional array with different nesting?

let arr = ;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Klimenko, 2020-05-10
@Antonio09

function findSum(arr) {
    const arrSum = arr.map(subArr => subArr.flat(Infinity).reduce((subSum, item) => (subSum + item)));
    return arrSum;
}

E
Evgeny Petrov, 2020-05-10
@kazsat

function arrSum(array) {
    let sum = 0
    function recur (array){
        if (Array.isArray(array)) {
            array.map(val => {
                
                if(Array.isArray(val)) {
                    recur(val)
                } else {
                    sum += val
                }
            })
        }
    }
    recur(array)
    return sum
}

let arr = , [3, 4], [5, 6]]
let totalSum = arrSum(arr)      \\ => 29

Total amount with any level of nesting

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question