一、题目
给定一组数据
[ "2022-02-11", "2022-02-09", "2021-12-29", "2021-12-30", "2021-12-31", "2022-01-01", "2022-01-05", "2022-01-06", "2022-01-07", "2022-02-11", "2022-02-11", "2022-02-11", "2022-02-11", "2022-02-12"]
要求将连续的日期统计为一个时间段(时间段开始结束日期相同只写一个日期) 输出数组
["2021-12-29至2022-01-01","2022-01-05至2022-01-07","2022-02-11至2022-02-12"]
二、解题思路
1、首先对数组进行去重操作
鉴于是字符串,直接采用扩展运算符+Set去重
timeArr = [...new Set(timeArr)]
2、对时间进行排序
将时间转化为时间戳,然后升序排列,为了方便后续调用,把原字符串存储进新数组
let tempObj = timeArr.map(item => {
let o = {}
o.key = item
o.value = Date.parse(new Date(item).toString()) / 1000
return o
})
tempObj.sort((a, b) => a.value - b.value)
3、比较相邻两个时间戳差值,标记出相邻一天的时间
这一步中,生成的数组的每一项采用对象形式,以布尔值代表连续与否,另一项作为操作字符
let tempResult = []
tempObj.forEach((item, index) => {
if(index + 1 == tempObj.length){
return
}
let start = item.value
let end = tempObj[index + 1].value
let Boolean = end - start == 24 * 60 * 60
tempResult.push({item:`${item.key}至${tempObj[index+1].key}`, Boolean})
})
console.log(tempResult)
4、对日期连续的选项进行合并
设定结果数组 本步思路
根据布尔值判断,
为true时,本项字符串与result数组最后一项字符串合并
为false时,判断result最后一项是否为空字符,若为空字符,则本项不做处理,若非空字符,则在rusult数组中推入空字符作为最后一项
初始result为空时,result没有上一项,所以初始情况直接推入空字符作为第一项 数组长度为零
let result = []
tempResult.forEach(item => {
if(!result.length){result.push('')}
if(item.Boolean){
result[result.length - 1] = `${result[result.length - 1]}至${item.item}`
}else if(result[result.length - 1] !== ''){
result.push('')
}
})
console.log(JSON.parse(JSON.stringify(result)))
5、result数组每项修正
去除空字符串(防止tempResult最后一项是false时,push进的''),截取每项第一个时间字符串与最后一个时间字符串
result = result.filter(i=>i).map(item => {
return `${item.slice(1,12)}${item.slice(item.length - 10, item.length)}`
})
console.log(result)
三、完整答案
let timeArr = [
"2022-02-11",
"2022-02-09",
"2021-12-29",
"2021-12-30",
"2021-12-31",
"2022-01-01",
"2022-01-05",
"2022-01-06",
"2022-01-07",
"2022-02-11",
"2022-02-11",
"2022-02-11",
"2022-02-11",
"2022-02-12"
]
timeArr = [...new Set(timeArr)]
let tempObj = timeArr.map(item => {
let o = {}
o.key = item
o.value = Date.parse(new Date(item).toString()) / 1000
return o
})
tempObj.sort((a, b) => a.value - b.value)
let tempResult = []
tempObj.forEach((item, index) => {
if(index + 1 == tempObj.length){
return
}
let start = item.value
let end = tempObj[index + 1].value
let Boolean = end - start == 24 * 60 * 60
tempResult.push({item:`${item.key}至${tempObj[index+1].key}`, Boolean})
})
console.log(tempResult)
let result = []
tempResult.forEach(item => {
if(!result.length){result.push('')}
if(item.Boolean){
result[result.length - 1] = `${result[result.length - 1]}至${item.item}`
}else if(result[result.length - 1] !== ''){
result.push('')
}
})
result = result.filter(i=>i).map(item => {
return `${item.slice(1,12)}${item.slice(item.length - 10, item.length)}`
})
console.log(result)