根據(jù)源數(shù)據(jù)里的時(shí)間戳進(jìn)行分組,按年、日進(jìn)行分組,年為大分組,然后再根據(jù)日期進(jìn)行分組
原文:https://mp.weixin.qq.com/s/iuecyqnT10w66h13xLXwsQ
1、源數(shù)據(jù)格式
正常的單層數(shù)組,只有時(shí)間戳,時(shí)間倒序
[
{
time: 1602139800000,
desc: "2020-10-08的數(shù)據(jù)"
},
{
time: 1633414800000,
desc: "2021-10-05的數(shù)據(jù)1111111"
},
{
time: 1634546100000,
desc: "2021-10-18的數(shù)據(jù)"
},
{
time: 1633415400000,
desc: "2021-10-05的數(shù)據(jù)2222222"
}
]
2、想要的數(shù)據(jù)格式
按年、日進(jìn)行分組,時(shí)間倒序
[{
date: "2021",
list: [
{
date: "10.18",
list: [{ time: 1634546100000, desc: "2021-10-18的數(shù)據(jù)" }]
},
{
date: "10.05",
list: [
{ time: 1633414800000, desc: "2021-10-05的數(shù)據(jù)1111111" },
{ time: 1633415400000, desc: "2021-10-05的數(shù)據(jù)2222222" }
]
}
]
},{
date: "2020",
list: [
{
date: "10.08",
list: [{ time: 1602139800000, desc: "2020-10-08的數(shù)據(jù)" }]
}
]
}
]
3、實(shí)現(xiàn)分組方法
我們用到lodash中的groupBy等方法
import _ from 'lodash';
...
const groupByListByDate = (data, dateFormat, continueGroupBy) => {
return _(data)
.groupBy((item) => moment(item.time).format(dateFormat))
.map((item, date) => {
let list = item;
if (continueGroupBy) {
list = groupByListByDate(item, "MM.DD");
}
return {
date,
list
};
})
.reverse()
.value();
};
4、粗略的展現(xiàn)效果

適用于資訊、課表排期等場景
codepen源碼地址: