Skip to content
Advertisement

TypeError: Cannot read properties of undefined (reading ‘length’) – Would like an explanation of why the code is saying this

Task : to create a function that removes the outer element of an array if the inner array contains a certain number. i.e filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18) should return [[10, 8, 3], [14, 6, 23]]

I would like an explanation as to what exactly the code is doing/reading when causing this error as opposed to just a solution, if possible.

I have included my thought process as notes in this code – so hopefully if i’m wrong somewhere, it can be pointed out.


function filteredArray(arr, elem) {
  let newArr = [];
  // Only change code below this line
  newArr = [...arr]; //copying the arr parameter to a new arr

 for (let i=0; i< newArr.length; i++){  //iterating through out array 
   for (let x= 0; x< newArr[i].length; x++){  //iterating through inner array 
     if(arr[i][x] === elem){    //checking each element of the inner array to see if it matches the elem parameter
      newArr.splice(i, 1);  //if true, removing the entire outer array the elem is inside
     } 
   } 

 }
  // Only change code above this line
  return newArr;
}

console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

Advertisement

Answer

When you are in the last iteration and found the value, you split the outer array and iterate still the inner array, but with the original index of the outer array. By shrinking the length, it points now over the length and any try to access undefined with a property goes wrong.

To overcome this and keeping the outer indices right, you could start from the last index and iterates backwards.

In addition to that, you could break the inner seach, becaues on find, you need not more to iterate this array.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement