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

前端 未结 3 1065
梦如初夏
梦如初夏 2020-12-31 06:28

I have an array of cars.

car = {
    make: \"nissan\",
    model: \"sunny\",
    colour: \"red\"
};

How would I use underscore.js to grou

3条回答
  •  生来不讨喜
    2020-12-31 06:49

    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" });
    

提交回复
热议问题