lodash 實(shí)現(xiàn)數(shù)組根據(jù)時(shí)間戳按年、日進(jìn)行分組

根據(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源碼地址

https://codepen.io/itguliang-the-selector/pen/qBXYGoo

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容