Finding the sum of a nested array

2019-06-02 09:01发布

I tried finding the sum of all numbers of a nested array, but I don't get it to work correctly. This is what I tried:

function arraySum(i) {
    sum=0;
    for(a=0;a<i.length;a++){
        if(typeof i[a]=="number"){
            sum+=i[a];
        }else if(i[a] instanceof Array){
            sum+=arraySum(i[a]);
        }
    }
    return sum;
}

Does somebody know where there is a mistake in it? When you try it out with the array [[1,2,3],4,5], it gets 6 as answer, instead of 15. I don't know why.

7条回答
做自己的国王
2楼-- · 2019-06-02 09:20

You're missing two var in there. You've implicitly declared sum and a at window scope:

function arraySum(i) {
    **var** sum=0;
    for(**var** a=0;a<i.length;a++){
        if(typeof i[a]=="number"){
            sum+=i[a];
        }else if(i[a] instanceof Array){
            sum+=arraySum(i[a]);
        }
    }
    return sum;
}
查看更多
太酷不给撩
3楼-- · 2019-06-02 09:20
from __builtin__ import int
def nestedLists(mylist):
    sum = 0
    if checkIfAllInt(mylist):
        result = addList(mylist)
        return result
    else:
        for value in mylist:
            sum = sum + nestedLists(value)
    return sum        

def addList(listdata):
    if(type(listdata) is int):
        return listdata
    else:
        return sum(listdata)    

def checkIfAllInt(listdata):
    check = True
    if(type(listdata) is int):
        return check
    else:
        for value in listdata:
            if(not type(value) is int):
                check = False
                return check
    return check    

print nestedLists([1,[2,3,[4,5,[6,7]]]])    
查看更多
我命由我不由天
4楼-- · 2019-06-02 09:30

The problem with your code is that the sum and a variables are global, instead of local. Because of this you get an infinite loop (a from the first entry in the function is reset by the second entry, so the same elements are processed again).

Fix it by adding var to where sum and a are declared to make them local to the function:

function arraySum(i) {
    var sum=0; // missing var added
    for(var a=0;a<i.length;a++){ // missing var added
        if(typeof i[a]=="number"){
            sum+=i[a];
        }else if(i[a] instanceof Array){
            sum+=arraySum(i[a]);
        }
    }
    return sum;
}

Demo: http://jsbin.com/eGaFOLA/2/edit

查看更多
劫难
5楼-- · 2019-06-02 09:32

Recurse, for example

function arraySum(x) {
    var sum = 0, i;
    if (typeof x === 'number')
        return x;
    else if (x instanceof Array)
        for (i = 0; i < x.length; ++i)
            sum += arraySum(x[i]);
    return sum;
}
arraySum([[1,2,3],4,5]); // 15

I didn't optimise this so that it's clear, you may want some more logic before recursion.


The reason yours isn't working is because you need to var both sum and a.

查看更多
smile是对你的礼貌
6楼-- · 2019-06-02 09:38

First of all why you use 'i' as input to function? we using 'i' to denote running index.. Regarding your question,you want 'a' to be local in your loop so instead of "for(a=0;..." instead write "for(var a=0;"

    <html>
    <body>
        <script>
            function NestedArraySummation(arr)
            {
                var sum=0;
                for(var i=0;i<arr.length;i++)
                {
                    if(typeof arr[i]=="number")
                    sum=sum+arr[i];
                    else  if(arr[i] instanceof Array)
                        sum=sum+NestedArraySummation(arr[i]);
                }
                    return sum;
            }

            var MyArray=[1,[2,3],4,10,[1,2]];
            var Sum=NestedArraySummation(MyArray);
            document.write(Sum);

        </script>
    </body>
</html>
查看更多
唯我独甜
7楼-- · 2019-06-02 09:38

For 2018 this solution is clean and functional:

let arr = [[1,2,3],4,5]
arr.flat().reduce((accumulator,currentValue)=>accumulator+currentValue)

Documentation for flat and reduce.

查看更多
登录 后发表回答