简体   繁体   中英

Group array of objects by multiple properties with Lodash

is possible with lodash library group elements by 2 properties? I have array of objects like this:

[{
   id: 1,
   amount: 2000,
   date: "2018-01-31T00:00:00.000Z"
},{
   id: 2,
   amount: 3000,
   date: "2017-07-31T00:00:00.000Z"
},{
   id: 3,
   amount: 6000,
   date: "2018-01-31T00:00:00.000Z"
},{
   id: 4,
   amount: 7000,
   date: "2017-01-31T00:00:00.000Z"
},{
   id: 5,
   amount: 5000,
   date: "2017-03-31T00:00:00.000Z"
},{
   id: 6,
   amount: 3000,
   date: "2018-02-22T00:00:00.000Z"
},{
   id: 7,
   amount: 4500,
   date: "2017-01-31T00:00:00.000Z"
}]

My goal is group objects in array by:

  1. year
  2. month

Purpose of that grouping is that I need in result order these objects' sum of amount by newest. So for that reason I need distinguish January 2017 from January 2018. It should be 2 different groups.

I am not sure if my approach is correct so I write here my required output:

[
  3000, // sum of 2018-2
  8000, // sum of 2018-1
  3000 // sum of 2017-7
  5000 // sum of 2017-3
  11500 // sum of 2017-1
]

I tried following command but it doesn't work and give me error:

  let xxx = _(data)
    .groupBy(function(i) {
      new Date(i.date).getFullYear()
    })
    .groupBy(function(i) {
      new Date(i.date).getMonth()
    })
    .map(x => x.amount)
    .sum()
    .orderBy('date').value();

Can you help me to fix it ? Thanks.

You can just concat your year and month with groupBy and use it.

var grouped = _.groupBy(data, function(i) {
  return new Date(i.date).getFullYear()+'-'+new Date(i.date).getMonth()
})

var resultUnsorted = _.map(t, (val, key) => ({key: key, val: val.reduce((p, c) => c.amount + p, 0) }));

then sort using _.orderBy

const output = _.orderBy(resultUnsorted, 'key');

you can write your custom sort function using the behaviour you want.

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