Reputation: 303
I'm trying to create a function that takes an array containing nested arrays and a number. The array I'm using as a parameter represents the times at which different students showed up to a class, each nested array is a set of times. The number represents the minimum of students that need to show up for the class to begin. The values inside each nested array are numbers, these numbers need to be either 0 or a negative. If the amount of 0's and negatives is equal to or larger to the number of students required for the class to start, then the function should push a true boolean into an array which the function will be returning later. If there aren't enough students, it has to push a false boolean into the same array. So if we have 3 nested arrays, the first containing enough students, and the two others don't, the return should end up being [true, false, false]. This is what I've written so far:
function openings (arrayOfTimes, studentsRequired){
const openWhen = [];
for (let i = 0; i <= arrayOfTimes.length; i++){
var x = arrayOfTimes[i];
for (let j = 0; j <= x.length; j++){
let y = x[i];
let z = [];
if (y <= 0){
z.push(y);
}
let open = true;
if (z.length >= studentsRequired){
openWhen.push(open);
}
let notOpen = false;
if (z.length < studentsRequired){
openWhen.push(notOpen);
}
}
}
return openWhen;
}
console.log(openings([[1,2,0],[0,0,-1],[-2,-3,0]],2));
The output says "cannot read property length of undefined", seeing the error log it indicates that the undefined property is x.
This is my first time using both nested arrays and a for loop within another for loop. I appreciate any insight and explanation on where I went wrong. Thanks a lot.
Upvotes: 1
Views: 955
Reputation: 636
In your for loops, you are using i <= arrayOfTimes.length
and j <= x.length
. If you change these loops to use i < arrayOfTimes.length
and j < x.length
, they will work properly. Keep in mind that the first element of an array has an index of 0
, meaning the length of the array will always be 1 more than the maximum index of an array.
I've re-written the function to be a bit simpler, and I've tested it. It returns a boolean for each sub-array, true if the sub-array contains at least the minimum number of values less than 1.
function openings (timesArray, minimum) {
return timesArray.map((times) => {
return times.filter(time => time < 1).length >= minimum;
});
}
Your sample input
console.log(openings([[1,2,0],[0,0,-1],[-2,-3,0]],2));
// returns [ false, true, true ]
Upvotes: 4