2018-10-12 15:37:13 -04:00
---
title: Nesting For Loops
---
2019-07-24 00:59:27 -07:00
# Nesting For Loops
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
---
## Problem Explanation
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
#### Relevant Links
2018-10-12 15:37:13 -04:00
< ul >
< li > < a href = "https://guide.freecodecamp.org/certifications/javascript-algorithms-and-data-structures/basic-javascript/nest-one-array-within-another-array" > Nest One Array Within Another Array< / a > < / li >
< li > < a href = "https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/iterate-through-an-array-with-a-for-loop" > Iterate Through An Array With A For Loop< / a > < / li >
< li > < a href = "https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays" > Accessing Nested Arrays< / a > < / li >
< / ul >
2019-03-29 20:52:56 +01:00
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
---
## Hints
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
### Hint 1
Make sure to check with < code > length< / code > and not the overall array.
2018-10-12 15:37:13 -04:00
2019-03-29 20:52:56 +01:00
### Hint 2
2018-10-12 15:37:13 -04:00
Use both < code > i< / code > and < code > j< / code > when multiplying the product.
2019-03-29 20:52:56 +01:00
### Hint 3
2018-10-12 15:37:13 -04:00
Remember to use < code > arr[i]< / code > when you multiply the sub-arrays with the < code > product< / code > variable.
2019-07-24 00:59:27 -07:00
---
## Solutions
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
< details > < summary > Solution 1 (Click to Show/Hide)< / summary >
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
```javascript
2018-10-12 15:37:13 -04:00
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
2019-07-24 00:59:27 -07:00
for (var i = 0; i < arr.length ; i + + ) {
for (var j = 0; j < arr [ i ] . length ; j + + ) {
2018-10-12 15:37:13 -04:00
product = product * arr[i][j];
}
}
// Only change code above this line
return product;
}
// Modify values below to test your code
2019-07-24 00:59:27 -07:00
multiplyAll([[1, 2], [3, 4], [5, 6, 7]]);
2018-10-12 15:37:13 -04:00
```
2019-07-24 00:59:27 -07:00
#### Code Explanation
2018-10-12 15:37:13 -04:00
< ul >
< li > We check the length of < code > arr< / code > in the < code > i< / code > for loop and the < code > arr[i]< / code > length in the < code > j< / code > for loop.< / li >
< li > We multiply the < code > product< / code > variable by itself because it equals 1, and then multiply it by the sub-arrays.< / li >
< li > The two sub-arrays to multiply are < code > arr[i]< / code > and < code > j< / code > .< / li >
< / ul >
2019-07-24 00:59:27 -07:00
< / details >