Javascript:Nesting for Loops

function multiplyAll(arr) {
  var product = 1;
  // Only change code below this line
  for(var i=0;i<arr.length;i++){
    for(var q=0;q<arr[i].length;q++){
      product*=arr[i][q];
    }
  }
  // Only change code above this line
  return product;
}

// Modify values below to test your code
multiplyAll([[1,2],[3,4],[5,6,7]]);

I got this one and it is working.But i don’t know how it is working.Anyone please explain it!

I think you are having trouble with product*=arr[i][q]
see this image. this might help if not let me know.

here I0 I1 I2 is for 1st loop and q0 q1 q2 q3 q4 q5 for 2nd loop.

1 Like

could you please explain this image.i didn’t get it!

start with an array of 3 arrays
first for loop:
i = 0, arr length = 3
…second for loop:
…q = 0, arr [position 0] length = 2
…multiply product by element at
… …arr [position 0] element[ 0 ] , then …arr [position 0] element[1]
so, position[0] is the variable … i
and element[0] is the variable …q
since the first array element has 2 items,[1,2]… q starts at 0, goes to 1, then
stops because incrementing q to 2 … no longer is < the element length.
so i goes from 0 to 1, and you start all over with the new array at the next position.
i = 1 …the array at arr[1] is … [3,4] …and q is set back to 0 to check the first element?

did I just make it worse? lol

see
for loop 1------ i=0
-----for loop 2------- q=0;
--------product = 1* arr[i,q] i.e [0,0] i.e 1(see the img for position) so position = 11 i.e 1;
-----for loop 2--------- q=1;
------- product = 1
arr[i,q]i.e [0,1] i.e 2(see the img for position) so position = 12 i.e 2;
for loop 1---------- i=1
-----for loop 2---------q=0;(sorry,that q2 in image is actually q0 nd q3 is q1);
--------product = 2
arr[i,q] i.e [1,0] i.e 3 so position = 2*3 i.e 6;
and this will go like this until the condition bacome false.

1 Like