0

I don't know why why I'am getting this error :

TypeError: Cannot read property 'length' of undefined

I have defined e to 0 in the 1st loop. So what's the deal ?

function filteredArray(arr, elem) 
{
  let newArr = [];
  
  for(let e = 0; e < arr.length; e++)
  {
    for ( let j = 0; j < arr[e].length; j++)
    {
      if(arr[e][j] == elem)
      {
        arr.splice(e, 1);
      }
    }
    newArr = arr;
  }
  
  return (newArr);
}

EDIT : To give more context , I'am trying to remove an array from array of arrays if it contains the elem. Like :

filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18) should return [[10, 8, 3], [14, 6, 23]]

filteredArray([["trumpets", 2], ["flutes", 4], ["saxophones", 2]], 2) should return [["flutes", 4]]

filteredArray([["amy", "beth", "sam"], ["dave", "sean", "peter"]], "peter") should return [["amy", "beth", "sam"]]

filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3) should return []

izzypt
  • 170
  • 2
  • 16
  • 2
    What is `arr`? Please provide a [mcve]. It seems like `arr[e]` is undefined for some `e`. – jabaa Aug 14 '21 at 12:33
  • Have you tried console logging arr, e, and j right before your arr.splice() statement to see what their values are? Because `let` should mean e is available within that entire block including the inner loop. – Dillan Wilding Aug 14 '21 at 12:34
  • 1
    You are removing the last element of the outer array while you're still iterating over it. Run your code in your debugger to see the problem. – jabaa Aug 14 '21 at 12:43
  • 1
    The arr.splice(e, 1); is causing problems because you are removing an element fro the parent array, so the nested array would not exist more. You should put a break after the splice – AlexSp3 Aug 14 '21 at 12:44

0 Answers0