Iterate Through All an Array’s Items Using For Loops

function filteredArray(arr, elem) {
  let newArr = [];
  for(let i = 0; i < arr.length; i++){
    if(arr[i].indexOf(elem) >= 0){
      arr.splice(i, 1);
  newArr = arr;
  return newArr;

console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

So I have this for the challenge in the title. All other tests past, apart from this one which returns the array:

[ [ 1, 6, 3 ], [ 19, 3, 9 ] ]

when it should be an empty array.

Can someone please explain where I’m going wrong? I’ve stared at this for an hour and can’t work it out…

The task of this is to remove any nested array that has the element inside?..if so,i would suggest just pushing the arr[i] in newArr if the arr[i].indexof(elem) !== -1 and rreturn newArr

1 Like

You’re absolutely correct. And that is the solution that probably makes more sense. But I am trying to wrap my head around why this particular method doesn’t work. I keep trying to run through it and I would love someone to explain why it’s not working.
The fact that it works for all test arrays except one is especially annoying!

Oh ok,i misunderstood your point here…I’m not able to test your code right now but it’s not advisable to splice the given array because it alters it and becomes a mess…if i test it and find the exact problem,i will reply back

Thank you you’re a star friend.

1 Like

Splice removes elements, which then means you shift all of the elements past the deleted one. You end up skipping over elements. Because you deleted an element and then increased i.

1 Like

Oh you LEGEND. and just like that it clicks.

Thank you sir for your help. Much appreciated.

1 Like