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]);
}
}
This part of the code increments count beyond the length of hold[]
while (clothes[i][8] < hold[count][8]){
count ++;
};
stepping through manually:
< so count++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.lengthi<=(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(","));