Can someone tell me why my code doesn’t work just on filteredArray

Can someone tell me why my code doesn’t work just on filteredArray
0

#1
function filteredArray(arr, elem) {
 
  // change code below this line
  for ( let i = 0; i < arr.length; i++) {
    if (arr[i].indexOf(elem) !== (-1)) {
      arr.splice(i, 1);
    }          
  }
  // change code above this line
  return arr;
}

Can someone tell me why my code doesn’t work just on “filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)”


FreeCodeCampBeta -Iterate Through All an Array's Items Using For Loops - Question
#2

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Let me walk you through what your code is doing in this example:

In the first iteration of the for loop i = 0. Your code checks if elem is in the first sub array of arr (arr[0]). The first sub array is [3, 2, 3] and three is in it it, so we execute the next line of code (see below):

arr.splice(i, 1);

Since i is still 0 at this point, the above splice deletes one element of arr starting at index 0. So, it is going to delete the first element of arr. What is the first element of arr? It is the sub array [3, 2, 3], so after deleting it, arr is now [ [ 1, 6, 3 ], [ 3, 13, 26 ], [ 19, 3, 9 ] ].

On the second iteration of the for loop, i = 1. Your code checks if elem is in the 2nd sub array of arr (arr[1]). The second sub array is [3, 13, 26] and 3 is in it, so we execute the splice again, with i being 1. The splice deletes the [3, 13, 26] sub array from arr, and arr is now [ [ 1, 6, 3 ], [ 19, 3, 9 ] ].

The for loop completes because at this point, arr.length is 2 and i becomes 2 at the beginning of the 3 iteration of the for loop.

To fix this issue, you should not be delete the sub array, but instead delete the item from the sub array.


#3

Thank you so much, i understood and solved the challenge perfectly.