Underscore.js如何一起做groupBy、filter、count?
How to do groupBy, filter, and count together in Underscore.js?
据我搜索,在Underscore.js
中,我们可以使用groupBy
函数。语法如下:
_.groupBy(list, iteratee, [context])
例如,我们这样做:_.groupBy(['one', 'two', 'three'], 'length');
那么,结果就是:{3: ["one", "two"], 5: ["three"]}
如您所见,结果包含 2 组。 现在,我想要的是:获取用于分组的标准,以及每个集合中的元素总数。
所以,结果应该是:{3: 2, 5: 1}
。因为 set 3
有 2 个元素,而 set 5
有 1 个元素。
我可以使用 Select
和 Count
在 LINQ 中轻松完成此操作。但我不知道如何在 Underscore.js
.
中执行此操作
感谢您的帮助。
如果我正确理解了问题,这应该有效:
_.each(
_.groupBy(['one','two','three'],'length'),
function(x,y,z){
z[y]=x.length;
}
);
您可以使用 _.countBy
method:
_.countBy(['one', 'two', 'three'], 'length');
// {3: 2, 5: 1}
根据文档,这符合您要实现的目标:
Sorts a list into groups and returns a count for the number of objects
in each group. Similar to groupBy, but instead of returning a list of
values, returns a count for the number of values in that group.
您可以使用 _.mapObject()
.
var grouped = _.groupBy(['one', 'two', 'three'], 'length');
var result = _.mapObject(grouped, function(items) {
return items.length;
}); // {3: 2, 5: 1}
据我搜索,在Underscore.js
中,我们可以使用groupBy
函数。语法如下:
_.groupBy(list, iteratee, [context])
例如,我们这样做:_.groupBy(['one', 'two', 'three'], 'length');
那么,结果就是:{3: ["one", "two"], 5: ["three"]}
如您所见,结果包含 2 组。 现在,我想要的是:获取用于分组的标准,以及每个集合中的元素总数。
所以,结果应该是:{3: 2, 5: 1}
。因为 set 3
有 2 个元素,而 set 5
有 1 个元素。
我可以使用 Select
和 Count
在 LINQ 中轻松完成此操作。但我不知道如何在 Underscore.js
.
感谢您的帮助。
如果我正确理解了问题,这应该有效:
_.each(
_.groupBy(['one','two','three'],'length'),
function(x,y,z){
z[y]=x.length;
}
);
您可以使用 _.countBy
method:
_.countBy(['one', 'two', 'three'], 'length');
// {3: 2, 5: 1}
根据文档,这符合您要实现的目标:
Sorts a list into groups and returns a count for the number of objects in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
您可以使用 _.mapObject()
.
var grouped = _.groupBy(['one', 'two', 'three'], 'length');
var result = _.mapObject(grouped, function(items) {
return items.length;
}); // {3: 2, 5: 1}