Iteratig through nested for loops // procedure

Dear coder,

again, I my brain stucks :confused:

Code:

function multiplyAll(arr) {

var product = 1;

// Only change code below this line

for (var i = 0; i < arr.length; i++) {

for (var j = 0; j < arr[i].length; j++) {

product *= arr[i][j];

}

}

// Only change code above this line

return product;

}

// Modify values below to test your code

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

Can someone explain the procedure of this code? As I mentioned before, solving the tasks often don`t makes people more wise…

product *= [0][0] okay, understood.

product *= [0][1] sorry, don`t get it.
How comes [0][1] is executed by this function?

Best regards

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

Say you have an array like arr = [1,2,3]

how would you get the first item in the array?
you would say arr[0] and that would get the first item.

so arr[0] returns 1 and arr[1] returns 2 …and so on right?

what if you array was now arr = [1,[9],3]
we would get the second item by saying arr[1] just like before

…but now arr[1] returns [9]

[9] is also an array.

cool.

what if you array was now arr = [1,[9, 7, 5],3]

how would you get the first item in the nested array at arr[1]

arr[1] returns [9,7, 5]
arr[1][0] returns 9

easy peasy

1 Like

Okay, understood.

My mind can`t figure out the following point:

function multiplyAll(arr) {

var product = 1;

for (var i = 0; i < arr.length; i++) {

for (var j = 0; j < arr[i].length; j++) {

product *= arr[i][j];

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

This function leads to:

  1. i = 0; j = 0 --> arr[0][0] --> product *= 1
  2. i = 1; j = 1 --> arr[1][1] --> product *= 3

I can`t explain my self how the function will procede arr[0][1].
Will be the inner loop be executed till end, until the outer loop changes to i = 1 ?
If so, arr.length is 3, but the arr[0] has just 2 values. So j = 2 or 3 leads to what?

Best regards

i is 0 so arr[0] is 1,2
	j is 0
	arr[0][0] is 1 so multiplying product by 1
	j is 1
	arr[0][1] is 2 so multiplying product by 2

i is 1 so arr[1] is 3,4
	j is 0
	arr[1][0] is 3 so multiplying product by 3
	j is 1
	arr[1][1] is 4 so multiplying product by 4

i is 2 so arr[2] is 5,6,7
	j is 0
	arr[2][0] is 5 so multiplying product by 5
	j is 1
	arr[2][1] is 6 so multiplying product by 6
	j is 2
	arr[2][2] is 7 so multiplying product by 7
for (var i = 0; i < arr.length; i++) { 
// arr[i] returns arr[0], arr[1], arr[2], etc
 
 for (var j = 0; j < arr[i].length; j++) { 
 // when i = 1, arr[1][j] returns arr[1][0], arr[1][1], arr[1][2], etc 

    // for every number arr[i][j] returns, perform a task

    product *= arr[i][j]; 
    // same as product = product * arr[i][j]
  }
}