JavaScript problem help

Tell us what’s happening:

I get what’s going with the problem but the If part of the solution given to the problem doesn’t make sense to me.

So for the if part it is saying if index of the elem given == -1 then push that arr[i] into the new arr. I understand that when using indexOf(elem) if a an element isn’t there it would be equal to -1. So for this part of the problem wouldn’t it push the elements that aren’t there to the new
array, isn’t push only adding elements to the end of an array?I don’t see anywhere in the code solution where they are removing the elements or filtering out what isn’t there.

Your code so far

//this is the solution

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

  // change code above this line

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36.

Challenge: Iterate Through All an Array’s Items Using For Loops

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops

It’s not removing anything from arr. This solution is creating a new array. It is building that array by only adding sub-arrays that do not contain elem.

1 Like

You will be both removing the sub-arrays that contain ‘elem’, so there needs to be one of those methods for removing array items. Then also the new array with the filtered items will need to be created and returned. A two step problem :wink:

1 Like