简体   繁体   中英

GroupBy array and then sortBy date that array using lodash

I have an array like so:

[
  {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"},
]

Now I want GroupBy date, then sortBy date newest, here is my code, I'm using lodash

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

The array result of code above like:

[
  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"}
     ]
]

But I would like the array to return like below:

[
  {
    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"}
     ]
  }
]

How I can do this with lodash.

Thank for your answer.

If vanilla JS solution works for you, you can make use of Array.prototype.reduce() to group your objects and Array.prototype.sort() to sort the 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%;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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