Search code examples
sum

Trying to add all the elements of two-dimensional array


sum([[1]]) returns 1, but sum([[1, 2], [3]]) does not return 6, but 1. I am not able to find the problem here i am new to programming

function sum(d) {
let into = 0;
for (let i = 0; i < 5; i++) {
    for (let j = 0; j < 5; j++) {
        into = into + d[i][j];
        return into
    }
}

}


Solution

  • So here's the deal: you need to loop through both arrays and pick up elements.

    let d =[[1,2],[3]]
    
    
    function sum(d) {
    let into = 0;
    for (let i = 0; i < d.length; i++) {
        for (let j = 0; j < d[i].length; j++) {
            into += d[i][j];
            
          
        }
    }
      console.log(into)
     }  
    
    sum(d)