Home > Blockchain >  TypeError: Cannot read properties of undefined (reading 'length') - Would like an explanat
TypeError: Cannot read properties of undefined (reading 'length') - Would like an explanat

Time:11-26

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

CodePudding user response:

This error occurs when you try to access a property on a variable that is undefined.

It's likely that you are getting this from your line:

for (let x= 0; x< newArr[i].length; x  ){

If your argument arr is not an array, then newArr[0] will be undefined and so `newArr[0].lenght will throw this error.

CodePudding user response:

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.

  • Related