Here is a nested array [[1,5], [2,4], [6,8], [7,7]]
, and I need to compare each items second index (departure
) to the following items first index (arrival
) like so: 5 >= 2
, 4 >= 6
, 8 >= 7
and finally 7 >= 1
.
My code on the other hand only compares once (so [1,5]
and [2,4]
) and omits the rest.
Please don't mind the rest of the code; it doesn't really make sense as it's just a draft and right now I just need to know how the customers (departure
) and (arrival
) times can be compared continuously. I was thinking of using a while loop instead of an if statement but I keep getting
fatal error: javascript heap out of memory'
console.log(allocateRooms([[1,5], [2,4], [6,8], [7,7]]));
function allocateRooms(c) {
let s = c.sort((a, b) => a[0] - b[0])
let rooms = [];
for (let i = 0; i < s.length; i++) {
for (let j = i + 1; j < s[i].length; j++) {
let depart = s[i][1];
let arrive = s[j][0];
if (depart >= arrive) {
rooms.push(s.indexOf(s[i]) + 1)
rooms.push(s.indexOf(s[j]) + 1)
} else {
rooms.push(0)
}
}
}
return rooms
}
You can do something like this
let arr = [
[1, 5],
[2, 4],
[6, 8],
[7, 7],
];
for (let i = 0; i < arr.length; i++) {
let depart = arr[i][1];
let arrive = arr[i + 1 === arr.length ? 0 : i + 1][0];
console.log(depart, arrive);
//your compare logic
}
Working sample: https://stackblitz.com/edit/vitejs-vite-daf2tz?file=main.js