Basic Data Structures: Iterate Through All an Array's Items Using For Loops - Don't understand error message

Hi all

When I run this code:

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

    }
  }

  // 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));

I get the error message:

filteredArray.js:5 Uncaught TypeError: Cannot read property 'length' of undefined
    at filteredArray (filteredArray.js:5)
    at filteredArray.js:18

I can’t figure out why newArr[i].length always returns this error message.

I would appreciate some insight.

(And yes, I get that there are other ways to get to the solution that do not involve using a nested loop, but for now I am keen to understand this error message for my own learning, rather than passing the exercise).

Cheers!

indexOf() returns a number, the first index of the element in the array, or -1 if it is not in the array. You use it in an if statement without a comparison: the if statement is always executed, but not when the element is at index 0.

splice() is also used in the wrong way, you get that error because splice() is removing elements from newArr (Mutating the array to which is applied) so at one point newArray[i] is undefined and cant have a length property

See if you can fix it from the documentation: