Iterate Through All an Array's Deletes only one array

Iterate Through All an Array's Deletes only one array
0

#1

Tell us what’s happening:
It deletes the array only if the elem is found just once.
So it works when elem = 19. But not when it needs to iterate again.
It then gives an error:
‘Cannot read property ‘length’ of undefined’
I think in the next iteration it tries to find ‘i’ but it’s not there.
I don’t really understand what is happening.
If someone can explain I would appreciate it.

Your code so far


function filteredArray(arr, elem) {
  let newArr = [];
  // change code below this line
  for (let i = 0; i < arr.length; i++){
    for (let j = 0; j < arr[i].length; j++) {
      if (arr[i][j] === elem) {
        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]], 19));

Your browser information:

User Agent is: Chrome/69.0.3497.100 .

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


#2

Well I found a solution.
I just have to use ‘break’.

arr.splice(i--, 1); newArr = [...arr] break;


#3

But do you understand why you must use break?


#4

Thank you for the question and for the interest.

On every iteration, I delete a sub array starting from the end.
At some point the code looks for an arr[i] that was deleted, like it still existed,
but it doesn’t, so it cannot get its length, and gives a TypeError.

If 19 was e.g. at the second subarray, the code would assign the first subarray to the newArr and then, at the next iteration, give the same error.

I hope my explanation was good enough. Or is there anything else you would like to explain?
I would appreciate any extra info.