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

302
Views
How can I get rid of error - TypeError: Cannot read property '8' of undefined

The while statement keeps throwing an error (TypeError: Cannot read property '8' of undefined) however the console.log still outputs the result that it's meant to.

 var hold = [];
 for (let i = 0; i < (clothes.length - 1); i++) {
   let count = 0;
   if (hold.length === 0) {
     hold.push(clothes[i]);
   } else {
     console.log(clothes[i][8], hold[count][8]);
     while (clothes[i][8] < hold[count][8]) {
       count++;
     }
     hold.slice(count, 0, clothes[i]);
   }
 }
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

This part of the code increments count beyond the length of hold[]

while (clothes[i][8] < hold[count][8]){
  count ++;
};

stepping through manually:

  • clothes[0] gets added as hold[0] by the "if hold is empty clause"
  • clothes[1] gets compared with hold[0] and is < so count++
  • clothes[1] gets compared with hold[1], but there's no hold[1], so you get the error

Add a clause in the while

while (count < hold.length && clothes[i][8] < hold[count][8]){
  count ++;
};

Note the length check must be first otherwise you still get the same error (there's other ways such as break out of the while). The 2nd part of the && is only valuated if the first part is true.


You have other issues stopping a complete solution:

for (let i = 0; i < (clothes.length - 1); i++){

will loop to the length-1, so if you have 3 elements, you only get two. You need to use either

  • i<clothes.length
  • i<=(clothese.length-1)

and

hold.slice(count, 0, clothes[i]);

is not the syntax for .slice and slice returns a new array, does not change the array in place. This should be

hold.splice(count, 0, clothes[i]);

Giving an updated snippet:

var clothes = [[2],[1],[3]];

var hold = []
for (let i = 0; i < clothes.length; i++) {
  var count = 0;
  if (hold.length === 0) {
    hold.push(clothes[i]);
  } else {
    while (count<hold.length && clothes[i][0] < hold[count][0]) {
      count++;
    };
    if (count == hold.length) {
      hold.push(clothes[i])
    }
    else  {
      hold.splice(count, 0, clothes[i]);
    }
  }
}
console.log(hold.join(","));

about 4 years ago · Santiago Gelvez 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!