Let's break this down for a bit; the first thing to do is to define a function that returns pairs of items from an array, like this:
function timePairs(times)
{
const result = []
// i gets incremented by two each time, so make sure there are enough items
// to pick
for (let i = 0, n = times.length; i + 2 <= n; i += 2) {
result.push([times[i], times[i + 1]])
}
return result
}
The resulting array would look like this:
[['11:00', '13:00'], ['15:00', '17:00'], ['19:00', '21:00']]
Then, each pair should be matched by a date; this can be accomplished by using a zip operation, which can be implemented using .map()
The map operation takes a function that gets called for each item, and it's expected to return the new value.
timePairs(times).map((pair, index) => {
return [dates[index], ...pair].join(',')
});
We use a small trick above; instead of writing [dates[index], pair[0], pair[1]]
, it uses the ...
operator to shorten the code.
All together, it looks like this:
const dates = ['2020-03-17','2020-03-19','2020-03-18','2020-03-12']
const times = ['11:00', '13:00','15:00', '17:00','19:00', '21:00', '23:00'];
function timePairs(times)
{
const result = []
for (let i = 0, n = times.length; i + 1 < n; i += 2) {
result.push([times[i], times[i + 1]])
}
return result
}
const result = timePairs(times).map((pair, index) => {
return [dates[index], ...pair].join(',')
});
console.log(result);
Faster!
You can do this with a single loop as well, just keep two pointers for dates & pairs:
const dates = ['2020-03-17','2020-03-19','2020-03-18','2020-03-12']
const times = ['11:00', '13:00','15:00', '17:00','19:00', '21:00', '23:00'];
result = []
for (let i = 0, j = 0, n = times.length >> 1; i != n; i++, j += 2) {
result.push(dates[i] + ',' + times[j] + ',' + times[j + 1])
}
console.log(result)