1

I was struggling with grouping my categories array in a collection like this example:

 var programs = [
   {
    name: 'a',
    categories: ['cat1', 'cat2']
   },
   {
    name: 'b',
    categories: ['cat2']
   },
   {
    name: 'c',
    categories: ['cat1', 'cat3']   
   }
];

If you do:

_.groupBy(programs, function(item){ return item.categories; });

It returns:

{
  'cat1, cat2': Array[1],
  'cat1, cat3': Array[1],
  'cat2': Array[1]
}

2 Answers 2

3

After searching over the Internet I tried it by my own and played with Underscore.js

Finally I got the solution which works for me:

var group = _.groupBy(_.flatten(_.pluck(programs, 'categories')), function(item){
    return item;
});

This returns:

{
  'cat1': Array[2], 
  'cat2': Array[2], 
  'cat3': Array[1]
}

http://jsfiddle.net/pypurjf3/2/

I hope this will help some people struggling with the same problem.

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

4 Comments

Nice timing :-) Exactly what I was looking for (literally, I had also multiple categories).
Apparently this doesn't solve my case, but regardless, gave insight and idea to pursue forward.
Do you have a fiddle for me? maybe i can help you.
but the array inside each key shows , for example: ['cat1', 'cat1'], and not the object you want. So, at the end, is not grouping your objects by categories. Did you find another way after this?
0

I had a similar problem, but wanted to do a bit more with how the grouping came out. Here's what I ended up with:

function groupByNested(theList, whichValue) {
  // Extract unique values, sort, map as objects
  var groups = _.chain(theList).pluck(theList, whichValue).flatten().uniq().reject(function(v) { return v==''; }).sort().map(function(g) { return { group: g, items: [] }; }).value();
  
  // Iterate through the array and add applicable items into the unique values list
  _.each(_ls.plants, function(p) {
    _.each(p[whichValue], function(v) {
      theGroup = _.find(groups, function(g) { return g.group == v; });
      theGroup.items.push(p);
    });
  });
  return groups;
}

Comments

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.