I have an array of cars.
car = {
make: "nissan",
model: "sunny",
colour: "red"
};
How would I use underscore.js to group the array by colour?
I've tried a few combos but I'm not really sure how to specify my iterator condition:
var carsGroupedByColor = _.groupBy(cars, false, colour);
var carsGroupedByColor = _.groupBy(vars, false, function(cars){ return cars[colour]; };
They all return everything in the array each time.
cars.groupBy (car => {...}) returns an object where each property has the key as company name and value as an array with the cars from the corresponding company. If you want to group data into a Map, you can use the method array.groupByToMap ().
array.groupByToMap (callback) works exactly like array.groupBy (callback), only difference is groups items into a Map instead of a plain JavaScript object. For example, grouping the cars array into a map by company name is performed as follows:
Because grouping data is an often occuring task (recall GROUP BY from SQL?) the array group proposal introduces two useful methods: array.groupBy () and array.groupByToMap (). Here's how you would use array.groupBy () to create the same grouping by category: Try the demo.
Note that the second parameter can either be a function or a string. If it's a string Underscore groups by that property name. 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.
You don't need the false
second argument, the following will work:
var redCars = _.groupBy(cars, 'colour');
Note that the second parameter can either be a function
or a string
. If it's a string
Underscore groups by that property name.
Taken from the docs:
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.
Here's a working example.
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