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

社会主义新天地 提交于 2019-12-18 12:55:02

问题


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.


回答1:


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.




回答2:


I've never used underscore js but would it not be as per their docs

var groupedCars = _.groupBy(cars, function(car) { return car.make; });

In fact I believe this ir more correct since it states that if the iterator is a string instead it groups by the property in the object with that string name.

var groupedCars = _.groupBy(cars, "make");

If you then want just the red cars (even though you really should be using a filter I guess) then you can do the following

var redCars = groupedCars["red"];

To use a filter instead

Looks through each value in the list, returning an array of all the values that pass a truth test (iterator). Delegates to the native filter method, if it exists.

var redCars = _.filter(cars, function(car) { return car.colour == "red" });



回答3:


var data = [
    {
        "name": "jim",
        "color": "blue",
        "age": "22"
    },
    {
        "name": "Sam",
        "color": "blue",
        "age": "33"
    },
    {
        "name": "eddie",
        "color": "green",
        "age": "77"
    },
    {
        "name": "Dheeraj",
        "color": "blue",
        "age": "25"
    },
    {
        "name": "Suraj",
        "color": "green",
        "age": "25"
    }
];

var result = _.groupBy(data,"color");
console.log(result);


来源:https://stackoverflow.com/questions/11582284/using-underscore-groupby-to-group-an-array-of-cars-by-their-colour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!