2018-10-12 15:37:13 -04:00
|
|
|
---
|
|
|
|
title: Iterate Through All an Array's Items Using For Loops
|
|
|
|
---
|
2019-07-24 00:59:27 -07:00
|
|
|
# Iterate Through All an Array's Items Using For Loops
|
|
|
|
|
|
|
|
### Hint 1
|
|
|
|
|
|
|
|
- A nested `for` loop must be used to search through every element in the array.
|
2018-10-12 15:37:13 -04:00
|
|
|
|
|
|
|
```javascript
|
2019-07-24 00:59:27 -07:00
|
|
|
for (let i = 0; i < arr.length; i++) {}
|
|
|
|
```
|
|
|
|
|
|
|
|
### Hint 2
|
2018-10-12 15:37:13 -04:00
|
|
|
- Every element of the array must then be compared to the `elem` parameter passed through the `filteredArray()` function.
|
|
|
|
```javascript
|
2019-07-24 00:59:27 -07:00
|
|
|
if (arr[i].indexOf(elem) == -1) {
|
|
|
|
}
|
2018-10-12 15:37:13 -04:00
|
|
|
```
|
2019-07-24 00:59:27 -07:00
|
|
|
### Hint 3
|
2018-10-12 15:37:13 -04:00
|
|
|
- If a match is NOT found then `newArr` have that entire subarray added. The `push()` function is very useful here.
|
|
|
|
```javascript
|
|
|
|
newArr.push(arr[i]);
|
|
|
|
```
|
|
|
|
- Once that entire subarray is added to `newArr` the loop continue with the next element.
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
---
|
|
|
|
## Solutions
|
|
|
|
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
|
|
|
|
2018-10-12 15:37:13 -04:00
|
|
|
```javascript
|
|
|
|
function filteredArray(arr, elem) {
|
|
|
|
let newArr = [];
|
|
|
|
// change code below this line
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
for (let i = 0; i < arr.length; i++) {
|
|
|
|
if (arr[i].indexOf(elem) == -1) {
|
|
|
|
//Checks every parameter for the element and if is NOT there continues the code
|
|
|
|
newArr.push(arr[i]); //Inserts the element of the array in the new filtered array
|
|
|
|
}
|
|
|
|
}
|
2018-10-12 15:37:13 -04:00
|
|
|
|
|
|
|
// change code above this line
|
|
|
|
return newArr;
|
2019-07-24 00:59:27 -07:00
|
|
|
}
|
2018-10-12 15:37:13 -04:00
|
|
|
// change code here to test different cases:
|
|
|
|
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));
|
|
|
|
```
|
2019-07-24 00:59:27 -07:00
|
|
|
</details>
|