function filteredArray(arr, elem) {
let newArr = [];
// Only change code below this line
for(let i = 0; i < arr.length; i++) {
//HERE is the line of code I am confused about. Can someone make a detailed explanation of each element in this statement?
if (arr[i].indexOf(elem) === -1) {
newArr.push(arr[i])
}
}
// Only change code above this line
return newArr;
}
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36.
Challenge: Iterate Through All an Array’s Items Using For Loops
if (arr[i].indexOf(elem) === -1)
checks if the element is in the inner array (arr[i])).
if the element is present it will return the index of elem if not it will return -1
so we are checking for elements that are not in array(-1) and pushing them into new array.
indexOf returns the first index at which the element is present in the array, if it isn’t it returns -1
so, arr[i] is the array being checked, elem is the element that could be in the array, and the === -1 is making so that if the element is not present (-1 === -1) everything evaluates to true and the if statement is executed