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.
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; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With