Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using underscore groupby to group an array of cars by their colour

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.

like image 954
Jon Wells Avatar asked Jul 20 '12 15:07

Jon Wells


People also ask

How do I Group cars by company in a map?

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 ().

What is the difference between array Array groupby and 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:

How do I Group data by category in an array?

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.

What is the difference between underscore and iterator?

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.


1 Answers

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.

like image 80
jabclab Avatar answered Sep 24 '22 15:09

jabclab