2

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.

1
  • 1
    Simply _.groupBy(data, x => x.date.slice(0, 7))... Commented Mar 19, 2018 at 12:40

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

this works thanks, but when I grouped objects and sum amount, how should I call orderBy ? there is no anymore date property :/
date key will be present which you can use for _.orderBy, since we are not mutating date.
But I also need to call map function to calculate amount, so when I join orderBy on the end of chain like this: *.orderBy(function() {console.log(o)}) It will be print just number value which I calculated in map ... so I am not able order by some property of previous object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.