我有两个数组。
第一个数组包含日期
['2020-03-17,2020-03-19,2020-03-18,2020-03-12']
Run Code Online (Sandbox Code Playgroud)
第二个数组包含时间,该数组由两个小时的时间段组成。
['11:00', '13:00','15:00', '17:00','19:00', '21:00', '23:00']
Run Code Online (Sandbox Code Playgroud)
最后,我需要结果如下所示:
['2020-03-17,11:00,13:00','2020-03-19,15:00,17:00','2020-03-18,19:00,21:00']
Run Code Online (Sandbox Code Playgroud)
如果两个数组都是有序的,并且每对时间都与一个日期相关联,则可以将日期索引乘以2得到第一次,然后加1得到结束时间。
let dates = ['2020-03-17', '2020-03-19', '2020-03-18', '2020-03-12']
let times = ['11:00', '13:00', '15:00', '17:00', '19:00', '21:00', '23:00']
let dateTime = [];
for (let i in dates) {
let timeIndex = i * 2;
let startTime = times[timeIndex]
let endTime = times[timeIndex + 1]
if (endTime)
dateTime.push( [dates[i], startTime, endTime].join(',') )
}
console.log(dateTime)Run Code Online (Sandbox Code Playgroud)
OP 中的数据存在需要解决或纠正的缺陷:
dates.pop().split(','))如果内部日期缺少时间会怎样?
让我们稍微分解一下;首先要做的是定义一个从数组中返回项目对的函数,如下所示:
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
}
Run Code Online (Sandbox Code Playgroud)
结果数组将如下所示:
[['11:00', '13:00'], ['15:00', '17:00'], ['19:00', '21:00']]
Run Code Online (Sandbox Code Playgroud)
然后,每一对都应该匹配一个日期;这可以通过使用zip 操作来完成,该操作可以使用.map()
地图操作采用一个为每个项目调用的函数,并且预计返回新值。
[['11:00', '13:00'], ['15:00', '17:00'], ['19:00', '21:00']]
Run Code Online (Sandbox Code Playgroud)
我们在上面使用了一个小技巧;[dates[index], pair[0], pair[1]]它不使用,而是使用...运算符来缩短代码。
总而言之,它看起来像这样:
timePairs(times).map((pair, index) => {
return [dates[index], ...pair].join(',')
});
Run Code Online (Sandbox Code Playgroud)
您也可以使用单个循环来完成此操作,只需保留两个日期和日期对的指针:
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);Run Code Online (Sandbox Code Playgroud)