js 将一个数组中的连续日期放在一起
首先对数组进行排序,然后通过比较相邻两个日期之间的时间差(单位为毫秒,一天等于 86400000 毫秒)来判断它们是否是连续的日期。如果是,则将它们放入同一个子数组中;否则就开辟一个新的子数组来存储下一个连续的日期。最终返回一个二维数组,每个子数组都包含一组连续的日期。
function sortDateList: function (data) {
data.sort(function (a, b) {
return new Date(a).getTime() - new Date(b).getTime()
})
return data
},
function handleDate (arr) {
// 转时间戳
function transTime (date) {
return new Date(date).getTime()
}
var result = []
var i = 0
const list = sortDateList(arr)
if (list.length === 0) return
list.forEach((item, index) => {
if (index === 0) {
result[0] = [item]
} else if (
transTime(item) - transTime(list[index - 1]) ===
86400000
) {
// 判断当前值 和 前一个值是否相差 1
result[i].push(item)
} else {
result[++i] = [item]
}
})
return result
}
handleDate(['2023-02-10','2023-02-01','2023-02-02','2023-02-04','2023-02-05','2023-02-08']) //返回结果:[['2023-02-01','2023-02-02'],['2023-02-04','2023-02-05'],['2023-02-08'],['2023-02-10']]