Why newArr is undefined?

Tell us what’s happening:

Hi. Could you, please, explain why it throws the error “TypeError: Cannot read property ‘length’ of undefined”

Your code so far


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


console.log(filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36.

Challenge: Iterate Through All an Array’s Items Using For Loops

Link to the challenge:

It’s because splice mutates newArray. When elem === newArr[i][j], and it’s last sub-array im the newArr, it removes the i-th sub-array. But for loop still tries to check if j < newArr[i].length for the same i that’s now higher than newArr length.

1 Like

Thank you! It makes sense