I’ve solved this exercise cause I was following the instruction given. but i don’t quite understand on the code im writing. could someone please help me to explain me the code please?
I’m wondering why we need another loop after the loop. and on the nested loop why do we use arr[i].length?
**Your code so far**
function multiplyAll(arr) {
let product = 1;
// Only change code below this line
for (let i = 0; i < arr.length; i++){
for (let j = 0; j< arr[i].length; j++) {
product = product * arr[i][j];
}
}
// Only change code above this line
return product;
}
console.log(multiplyAll([[1, 2], [3, 4], [5, 6, 7]]));
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36
hey there, thanks for responding, my understanding is that one for the first array and the second is the array within the array. not sure if im correct.
The input is an array of arrays (otherwise called a two dimensional array).
So if you imagine a 2-D table. It has rows and columns. To iterate over it, you need to go row by row, but also column by column.
And that’s why you need two for loops (one nested inside the other)
About terminology I am not sure, my english is little off.
run the below code somewhere, and look into console:
const twoDArray = [
[1, 2, 3],
[4, 5],
[6, 7, 8, 9]
]
for (let i = 0; i < twoDArray.length; i++) {
console.log(`the below is subarray with index ${i}`)
console.log(twoDArray[i]);
console.log(`it has length: ${twoDArray[i].length}`);
console.log('---');
for (let j = 0; j < twoDArray[i].length; j++) {
console.log(`the below is element with index ${j} of subarray mentioned above`);
console.log(twoDArray[i][j]);
console.log('---');
}
console.log('----------------');
}