# Basic Data Structures - Iterate Through All an Array's Items Using For Loops

I tried to do this the first time with: " if (arr[i].indexOf(elem) >= 0) ", thinking that if the result was true, then the element would pass on to the newArray.

From what i understood in the assignment, "if the element was indeed in one of the sub arrays, only then i would pass it to the new filtered array.

So how come i have to check if the element didn’t exist (on the IF statement) and then proceed to add things to the newArray like this? if (arr[i].indexOf(elem) == -1)

How was my logic wrong?

function filteredArray(arr, elem) {
let newArr = [];
// change code below this line

for (let i = 0; i < arr.length; i++) {
if (arr[i].indexOf(elem) == -1) {

newArr.push(arr[i]);
}
}

// change code above this line
return newArr;
}
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 OPR/102.0.0.0

Challenge: Basic Data Structures - Iterate Through All an Array’s Items Using For Loops

You should only be pushing arrays which do NOT contain elem.
If you use the condition if (arr[i].indexOf(elem) >= 0) you will push arrays which DO contain elem.

1 Like

No, opposite, you’re supposed to filter it out if it’s present, that’s why.

1 Like

Oh i see now, i got it all wrong from the beggining. Thank you very much!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.