5

I currently have an array that resembles the array below:

[
      {id:1,color:'red'},
      {id:2,color:'blue'},
      {id:3,color:'red'},
      {id:4,color:'green'},
      {id:5,color:'blue'},
]

I am looking for the fastest way to get something like below where I could split/sort the array by a property in the object, in this example it would be 'color' :

[
      [
        {id:1,color:'red'},
        {id:3,color:'red'},
      ],[
        {id:2,color:'blue'},
        {id:5,color:'blue'},
      ],[
        {id:4,color:'green'},
    ]
]

I could write a function for this but I was thinking there may be something to do this already in underscore.js, but had no luck finding it.

1
  • 2
    there is a groupBy function Commented May 22, 2014 at 20:07

3 Answers 3

2

You need to use the groupBy function of underscore you can find it in the docs right here.

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.

[
      {id:1,color:'red'},
      {id:2,color:'blue'},
      {id:3,color:'red'},
      {id:4,color:'green'},
      {id:5,color:'blue'},
]

_.groupBy(a, function(x){ return x.color; });
Sign up to request clarification or add additional context in comments.

3 Comments

That doesn't produce the requested output. Though, the OP may be fine dealing with it as is.
canon is correct, it returns an object but this should work just as well. Thanks.
The result of this needs to be wrapped in _.toArray() to get the desired output
0

You can get the required results using ES5 features without need of third party libraries:

var data = [
      {id:1,color:'red'},
      {id:2,color:'blue'},
      {id:3,color:'red'},
      {id:4,color:'green'},
      {id:5,color:'blue'},
];

var temp = {};
data.forEach(function(item){
    if (temp[item.color]) { 
         temp[item.color].push(item);
     } else {
       temp[item.color] = [ item ]; }   
});

var result = Object.keys(temp).map(function(key){ return temp[key]; });

In order to support older browsers use ES5 shims

Comments

0

You can combine the _.groupBy with the _.toArray function:

var dict = [
      {id:1,color:'red'},
      {id:2,color:'blue'},
      {id:3,color:'red'},
      {id:4,color:'green'},
      {id:5,color:'blue'},
];

var grouped = _.groupBy(dict, function(x){ return x.color; });
var result = _.toArray(grouped);

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.