Loops - Nesting For Loops

PHOTO EMBED

Tue Apr 26 2022 22:37:41 GMT+0000 (Coordinated Universal Time)

Saved by @Luduwanda #javascriptreact

//Remember that, for the inner loop, we need to check the .length of arr[i] since arr[i] is one of the sub-arrays we looked at earlier.

function multiplyAll(arr) {
  let product = 1;
  // Only change code below this line

  //Outer Loop
  for (let i = 0; i < arr.length; i++){
  //Inner Loop
    
  for (let j = 0; j < arr[i].length; j++){
    
  //Finally, multiply product by every element in each of the sub-arrays: 
  product *= arr[i][j]
  }
  }
  // Only change code above this line
  console.log(product)
  return product;
}

multiplyAll([[1, 2], [3, 4], [5, 6, 7]]);


//Closer look
//The overall view:
//Sub-array 0: 1,2
//Element 0: 1
//Element 1: 2
//Sub-array 1: 3,4
//Element 0: 3
//Element 1: 4
//Sub-array 2: 5,6,7
//Element 0: 5
//Element 1: 6
//Element 2: 7


//The first iteration of i grabs the first sub-array, [1, 2]. Then the first iteration of j goes through each element in that sub-array

// i is 0
arr[0] // [1, 2];

// j is 0
arr[0][0] // 1
// j is 1
arr[0][1] // 2

-----

// i is 1
arr[1] // [3, 4]

// j is 0
arr[1][0] // 3
// j is 1
arr[1][1] // 4

...


//To better understand arr[i][j] we can replace "arr[i]"" by "subarray"
function multiplyAll(arr) {
  let product = 1;
  // Only change code below this line
  for (let i = 0; i < arr.length; i++) {
    const subArray = arr[i];
    for (let j = 0; j < subArray.length; j++) {
      product *= subArray[j];
    }
  }
  // Only change code above this line
  return product;
}

multiplyAll([[1,2],[3,4],[5,6,7]]);

content_copyCOPY