1

I want to group my JavaScript array of objects by two attributes of the object contained within.

I have tried underscores groupBy and it seems to accept only one attribute at a time.

_.groupBy([{'event_date':'2013-10-11', 'event_title':'Event 2'}, {'event_date':'2013-01-11', 'event_title':'Event 1'}], 'event_title')

My question is... is there a way to group an array of objects by two of its attributes.

Like in Ruby

[#<struct Event event_date=2013-10-11, event_title=Event 2>, #<struct Event  event_date=2013-01-11, event_title=Event 1>].group_by{|p| p.event_date and p.event_title}
1
  • 2
    For those of us not familiar with the Ruby function, can you give an example of what output you're looking for? Commented Jul 26, 2013 at 16:55

1 Answer 1

5

From the fine manual:

groupBy _.groupBy(list, iterator, [context])

Splits a collection into sets, grouped by the result of running each value through iterator. If iterator is a string instead of a function, groups by the property named by iterator on each of the values.

So you can pass a function to _.groupBy and the results will be grouped by the result of that function. That just means that you need a function that will produce simple keys for your groups. Unfortunately, object keys in JavaScript are strings so you can't (reliably) use a function that returns an array of keys like you'd do in Ruby but you can kludge it a bit:

_(a).groupBy(function(o) {
    return o.event_title + '\x00' + o.other_key;
});

I'm guessing that '\x00' won't appear in your event_title but you can use whatever delimiter works for your data.

Demo: http://jsfiddle.net/ambiguous/hwg3p/

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

Comments

Your Answer

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