使用下划线groupby按颜色分组汽车数组 [英] Using underscore groupby to group an array of cars by their colour

查看:257
本文介绍了使用下划线groupby按颜色分组汽车数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列汽车。

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

我如何使用underscore.js按颜色对数组进行分组?

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.

推荐答案

你不需要 false 第二个参数,以下内容将起作用:

You don't need the false second argument, the following will work:

var redCars = _.groupBy(cars, 'colour');

请注意,第二个参数可以是 function string 。如果是字符串按该属性名称的下划线组。

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.

这是一个工作示例

这篇关于使用下划线groupby按颜色分组汽车数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆