Iterate Through Can't get empty array

I don’t see why i can’t get 4th check and my answer is 1,6,3,19,3,9 instead of empty array. I see pattern that only arrays with first number matched with element was deleted but i used indexOf method so i didn’t expect that. Can you give me a clue?

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

// change code here to test different cases:
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

not sure if you want to just filter the number as is, or return a single array without the number

short way - map() main array then filter() or map() nested arrays

long way -

loop though main array

loop through each nested array

if item !== elem, then push to new array (or splice to remove)

I can’t use map and filter. It is Basic Data Structures: Iterate Through All an Array’s Items Using For Loops task

This is a bad idea:

for (let i = 0; i < arr.length; i++) {
arr.splice(i, 1);

You are taking elements from the array while you’re looping through it. The last test doesn’t pass because after the second iteration, the arr contains only two elements and i is already 2, so i < arr.length doesn’t pass and you break out of the loop.

To solve this I’d invert your logic, instead of checking if the element exists in the array and then removing the sub-array, I’d check if the element doesn’t exist in the array like arr[i].indexOf(elem) === -1 and then push the sub-array into newArr.

1 Like

Thanks for clear explanation, now it worked