Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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
    }
}

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading