1

I have some data

var data = [ 
    {type: "A", role:[1,2]},
    {type: "B", role:[2]},
    {type: "C", role:[2,3]},
    {type: "D", role:[3]} 
];

I'm trying to sortBy 'role' using underscore.js

var groups = _(data).groupBy(function(el){
    return el.role
  }
);

Is there a easy way to get reapeated data like this

1: {
    {type:"A" ...}
},
2: {
   {type:"A" ...},
   {type:"B" ...},
... etc

not like this http://jsbin.com/IzEwUkim/2/edit

2 Answers 2

5

You can, as usual, do it by hand with _.reduce, something like this:

var groups = _(data).reduce(function(memo, o) {
    _(o.role).each(function(i) {
        memo[i] = memo[i] || [ ];
        memo[i].push(o);
    });
    return memo;
}, { });

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

You could use a plain for loop instead of _.each to iterate over the roles of course.

_.groupBy isn't going to work here as the function/key is always a single value so I think you're stuck unwrapping the role arrays by hand.

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

Comments

1

I know you asked for underscore, but here's native js:

var map = {};
data.forEach(function(obj){
  obj.role.forEach(function(roleVal){
    (map[roleVal] = map[roleVal] || []).push(obj);
  });
});
console.log(map);

1 Comment

You could also use the native reduce if you wanted to skip the separate var map = { }. Nothing wrong with native solutions.

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.