2018-09-30 23:01:58 +01:00
---
id: 56533eb9ac21ba0edf2244e1
title: Nesting For Loops
challengeType: 1
2019-02-14 12:24:02 -05:00
videoUrl: 'https://scrimba.com/c/cRn6GHM'
2019-07-31 11:32:23 -07:00
forumTopicId: 18248
2021-01-13 03:31:00 +01:00
dashedName: nesting-for-loops
2018-09-30 23:01:58 +01:00
---
2020-11-27 19:02:05 +01:00
# --description--
2018-09-30 23:01:58 +01:00
If you have a multi-dimensional array, you can use the same logic as the prior waypoint to loop through both the array and any sub-arrays. Here is an example:
2019-05-17 06:20:30 -07:00
```js
2021-10-26 01:55:58 +09:00
const arr = [
[1, 2], [3, 4], [5, 6]
2019-05-17 06:20:30 -07:00
];
2021-10-26 01:55:58 +09:00
for (let i = 0; i < arr.length ; i + + ) {
for (let j = 0; j < arr [ i ] . length ; j + + ) {
2019-05-17 06:20:30 -07:00
console.log(arr[i][j]);
}
}
```
2020-11-27 19:02:05 +01:00
This outputs each sub-element in `arr` one at a time. Note that for the inner loop, we are checking the `.length` of `arr[i]` , since `arr[i]` is itself an array.
# --instructions--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
Modify function `multiplyAll` so that it returns the product of all the numbers in the sub-arrays of `arr` .
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --hints--
2018-09-30 23:01:58 +01:00
2021-10-26 01:55:58 +09:00
`multiplyAll([[1], [2], [3]])` should return `6`
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert(multiplyAll([[1], [2], [3]]) === 6);
2018-09-30 23:01:58 +01:00
```
2021-10-26 01:55:58 +09:00
`multiplyAll([[1, 2], [3, 4], [5, 6, 7]])` should return `5040`
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert(
multiplyAll([
[1, 2],
[3, 4],
[5, 6, 7]
]) === 5040
);
```
2018-09-30 23:01:58 +01:00
2021-10-26 01:55:58 +09:00
`multiplyAll([[5, 1], [0.2, 4, 0.5], [3, 9]])` should return `54`
2020-11-27 19:02:05 +01:00
```js
assert(
multiplyAll([
[5, 1],
[0.2, 4, 0.5],
[3, 9]
]) === 54
);
```
# --seed--
## --seed-contents--
2018-09-30 23:01:58 +01:00
```js
function multiplyAll(arr) {
2021-10-26 01:55:58 +09:00
let product = 1;
2018-09-30 23:01:58 +01:00
// Only change code below this line
2018-10-08 01:01:53 +01:00
2018-09-30 23:01:58 +01:00
// Only change code above this line
return product;
}
2021-10-26 01:55:58 +09:00
multiplyAll([[1, 2], [3, 4], [5, 6, 7]]);
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
# --solutions--
2018-09-30 23:01:58 +01:00
```js
function multiplyAll(arr) {
2021-10-26 01:55:58 +09:00
let product = 1;
for (let i = 0; i < arr.length ; i + + ) {
for (let j = 0; j < arr [ i ] . length ; j + + ) {
2018-09-30 23:01:58 +01:00
product *= arr[i][j];
}
}
return product;
}
```