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

My browser lags when I try a loop function?

I wrote a simple nested loop function to multiply all items in an array and output the total value, but each time is I run a loop function my browser either crashes or doesn’t stop loading

function multiplyAll(arr){ 
        Let product = 1;
       for(let i = 0; i < 
            arr.length; i++){
            for(let j = 0; j < 
     arr[i].length; j *= product);
     }
      return product;
}

multiplyAll([[1], [2], [3]]);

>Solution :

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

You are creating an infinite loop here because of

for (let j = 0; j < arr[i].length; j *= product);

Here, j is always 0.

If you want to multiply all the nested value then you should do as:

function multiplyAll(arr) {
  let product = 1;
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr[i].length; ++j)
      product *= arr[i][j];
  }
  return product;
}

console.log(multiplyAll([[1], [2], [3]]));

If you just want to multiple all the nested value then you can simply do as:

function multiplyAll(arr) {
  return arr.flat().reduce((acc, curr) => acc * curr, 1);
  // If you want to get numbers at any depth then you can flat at any level
  // using Infinity as
  // return arr.flat(Infinity).reduce((acc, curr) => acc * curr, 1);
}

console.log(multiplyAll([[1], [2], [3]]));
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