Doble for loop not needed?

Hello everybody,
working on the session ‘iterate through all array’s elements using a for loop’, this is my question: if the exercise was about sub-arrays in one array, plus the ‘elem’ item, why to iterate through them is not needed a double for loop??

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

Thanks so much for your time!!
Cheers!

Hey, can you clarify which exercise is this? Providing a link to that will be handy

1 Like

You used a double loop though :wink:
You didn’t “write” two loops, but what do you think .indexOf(elem) does? It loops over an array to find the index. So someone else has written the second loop, but you are using it, by calling the method.

1 Like

Ok, so the first loop iterate through the array, while indexOf() iterate through elements within the sub-arrays?
Thanks so much, I got it now!! :pray:

1 Like

That’s https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops

However, someone already replied my question!
Thanks!!

Edit: I misread the instructions. Removed to prevent confusion for other folks down the line.

It’s still using a loop under the covers. That loop may break early, but it still is a loop.

Why would it always return a value that isn’t equal to -1?

It isn’t. indexOf() stops once it has a match.

Edit: I misread the instructions. Removed to prevent confusion for other folks down the line.

indexOf() stops when it has a match, not before.

Internally, it does something like this

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

But this method is called independently on each subarray. The subarrys don’t know about each other’s contents.

1 Like

Edit: I misread the instructions. Removed to prevent confusion for other folks down the line.

A return statement immediately stops function execution. The return statement inside of the loop triggers when a match is found.

Your example just doesn’t work the way you claim.

I think you are misunderstanding the goal of this challenge. If the target ‘elem’ is 3, you need to remove every single subarray that contains a 3.

1 Like

Edit: I misread the instructions. Removed to prevent confusion for other folks down the line.

It does not. It just does not do this at all in any way whatsoever.

This does not occur

It doesn’t.

I’m going back to edit my prior posts to avoid confusion for folks that come after.

I’m a dunce. I DID misunderstand the intended outcome of the project that it was removing the ELEMENTS that matched the elem value. I am now clear that it is removing the ENTIRE SUBARRAY if it finds that value anywhere in the subarray.

Full ownership for the confusion. I appreciate your patience.

No worries. We’ve all sworen the code did one thing when it actually did the opposite at one point or another.