Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split an array into arrays by an objects property using javascript?

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.

like image 230
Andrew Royce Avatar asked Nov 01 '22 23:11

Andrew Royce


1 Answers

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; });
like image 166
bobthedeveloper Avatar answered Nov 12 '22 14:11

bobthedeveloper