Mr. J
Mr. J

Reputation: 1839

Don't Understand why forEach cannot access Array its Looping Over

I have this code which needs to compare start and end times. The start and end times are in an array of objects. I need to drill into the objects to compare the values. Error is occurring on the if statement line. Seems like it cannot access the array that it is looping through. Why? I have added the arg to the loop to allow it to do so.

const schedule = [{ startTime: 540, endTime: 600}, {startTime: 550, endTime: 615}, {startTime: 645, endTime: 715}]
// >>> [{startTime: 615, endTime: 645}, {startTime: 715, endTime: 720}]

function findFreeTime(times) {
    const freeTime = []
    const bookings = times
    const timeSlot = {
        startTime: 0,
        endTime: 0
    }
bookings.forEach(function (element, index, array) {
        if (element.endTime <= array[index+1].startTime) {
            const newSlot = Object.create(timeSlot)
            newSlot.startTime = element.endTime
            freeTime.push(newSlot)
            console.log(freeTime)
        }
    });
    return freeTime
}

console.log(findFreeTime(schedule))

Upvotes: 0

Views: 260

Answers (2)

Abhimanyu
Abhimanyu

Reputation: 114

Just assume when forEach loop reached on last index. that time see your if condition

if (element.endTime <= array[index+1].startTime)

When we are trying to get startime (array[index+1].startTime) it's showing error. because because we are trying get startime form undefined. loop already reach on last index and we are trying to get value of (index + 1) which is undefined.

Upvotes: 0

Vibha Chosla
Vibha Chosla

Reputation: 713

You should add one more condition in your if statement like :

if (index < (array.length - 1) && element.endTime <= array[index+1].startTime) {

}else if (index == (array.length - 1)){
  // your logic for last record
}

Upvotes: 1

Related Questions