Can someone explain to me why my approach is not working

I’m solving the question: Iterate Through All an Array’s Items Using For Loops


I’ve seen the hint and was able to solve it but still struggling to find what was wrong with my approach.
function filteredArray(arr, elem) {
  let newArr = [];
  // Only change code below this line
  for(let i = 0; i < arr.length; i++){
    let a = arr[i];
    if(a.indexOf(elem) !== -1){
      arr.splice(i, 1);
    }
  }
  newArr = arr;
  // Only change code above this line
  return newArr;
}

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

My first thought is that you are removing elements from an array while you are using an index variable to go through it - you are changing it as you are trying to go through it. That is always problematic.

Instead of mutating the existing array, what if you created a new array and returned that. That is what is in the example and is a very common practice.

2 Likes

I was actually able to get your version to work by looping in the opposite direction. This works because you are removing an element after the next one you are checking instead of before, so the index for that doesn’t change. But I still think the non-mutating version is better.

1 Like