繁体   English   中英

GroupBy 数组,然后 sortBy 使用 lodash 确定该数组的日期

[英]GroupBy array and then sortBy date that array using lodash

我有一个像这样的数组:

[
  {id: "1", description: "Insurance", date: "2020-12-22T00:00:00Z"},
  {id: "2", description: "Salary", date: "2020-12-20T00:00:00Z"},
  {id: "3", description: "Interest", date: "2020-12-20T00:00:00Z"},
  {id: "4", description: "Panera", date: "2020-12-19T00:00:00Z"},
  {id: "5", description: "Citibank", date: "2020-12-18T00:00:00Z"},
]

现在我想要 GroupBy 日期,然后是最新的 sortBy 日期,这是我的代码,我正在使用lodash

const groups = _(list)
  .groupBy((trans) => moment(trans.date).format('MM/DD/YYYY'))
  .sortBy(group => list.indexOf(group[0]))
  .value();

上面代码的数组结果如下:

[
  0: [
       {id: "1", description: "Insurance", date: "2020-12-22T00:00:00Z"}
     ],
  1: [
       {id: "2", description: "Salary", date: "2020-12-20T00:00:00Z"},
       {id: "3", description: "Interest", date: "2020-12-20T00:00:00Z"}
     ],
  2: [
       {id: "4", description: "Panera", date: "2020-12-19T00:00:00Z"}
     ]
  
  3: [
       {id: "5", description: "Citibank", date: "2020-12-18T00:00:00Z"}
     ]
]

但我希望数组返回如下:

[
  {
    date: 12/22/2020,
    items: [
       {id: "1", description: "Insurance", date: "2020-12-22T00:00:00Z"}
     ]
  },
  {
    date: 12/20/2020,
    items: [
       {id: "2", description: "Salary", date: "2020-12-20T00:00:00Z"},
       {id: "3", description: "Interest", date: "2020-12-20T00:00:00Z"}
     ],
  },
  {
    date: 12/19/2020,
    items: [
       {id: "4", description: "Panera", date: "2020-12-19T00:00:00Z"}
     ]
  },
  {
    date: 12/18/2020,
    items: [
       {id: "5", description: "Citibank", date: "2020-12-18T00:00:00Z"}
     ]
  }
]

我怎么能用 lodash 做到这一点。

谢谢你的回答。

如果 vanilla JS 解决方案适合您,您可以使用Array.prototype.reduce()对对象进行分组,并使用Array.prototype.sort()对 output 进行排序:

 const src = [ {id: "5", description: "Citibank", date: "2020-12-18T00:00:00Z"}, {id: "1", description: "Insurance", date: "2020-12-22T00:00:00Z"}, {id: "2", description: "Salary", date: "2020-12-20T00:00:00Z"}, {id: "3", description: "Interest", date: "2020-12-20T00:00:00Z"}, {id: "4", description: "Panera", date: "2020-12-19T00:00:00Z"}, ], result = [...src.reduce((acc,o) => { const [yyyy, mm, dd] = o.date.split(/[\-T]/), key = [mm, dd, yyyy].join('/'), group = acc.get(key) group? group.items.push(o): acc.set(key, {date: key, items: [o]}) return acc }, new Map).values()].sort(({date:a},{date:b}) => b.localeCompare(a)) console.log(result)
 .as-console-wrapper{min-height:100%;}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM