admin管理员组

文章数量:1391929

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}

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}
Share Improve this question edited Jul 26, 2013 at 16:49 asked Jul 26, 2013 at 16:39 user365916user365916 1
  • 2 For those of us not familiar with the Ruby function, can you give an example of what output you're looking for? – freejosh Commented Jul 26, 2013 at 16:55
Add a ment  | 

1 Answer 1

Reset to default 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/ambiguous/hwg3p/

本文标签: javascriptUsing underscore groupby to group an array of objects by more than one attributeStack Overflow