Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!