数组中分组项和计数项的简洁方法 [英] Concise way to Group by and Count item in array
本文介绍了数组中分组项和计数项的简洁方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的数组:
const arr = [ {name: 'Server 1', country: 'DE'}, {name: 'Server 2', country: 'PL'},
{name: 'Server 3', country: 'US'}, {name: 'Server 4', country: 'DE'},
{name: 'Server 5', country: 'US'}];
我想要的是 group and count
以获得如下的输出:
What I want is group and count
to get the ouput like below:
[
{
"country": "DE",
"count": 2
},
{
"country": "PL",
"count": 1
},
{
"country": "US",
"count": 2
}
]
当前,我正在使用 lodash
,但是我认为有更好的方法(例如,使用 _groupBy
或类似的方法)来解决它,对吧?
Currently, I'm using lodash
but I think there are better ways (for example, using _groupBy
or something like that) to resolve it, right?
我的代码在这里:
const arr = [ {name: 'Server 1', country: 'DE'}, {name: 'Server 2', country: 'PL'}, {name: 'Server 3', country: 'US'}, {name: 'Server 4', country: 'DE'}, {name: 'Server 5', country: 'US'}];
const objectGroupby = _.countBy(arr, 'country');
const result = Object.entries(objectGroupby).map(([key, value]) => ({country: key, count: value}));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
如您所见, _.countBy(arr,'country')
只是返回一个对象而不是数组.
As you can see, _.countBy(arr, 'country')
just returns an object instead of an array.
{
"DE": 2,
"PL": 1,
"US": 2
}
然后我必须使用 Object.entries()
& map
来解决它.
Then I have to use Object.entries()
& map
to resolve it.
推荐答案
万岁!!!
最近几天研究之后,我终于像这样使用 groupBy
找出了解决方案.
After researching in recent days, I finally figure out the solution using groupBy
like this.
const arr = [ {name: 'Server 1', country: 'DE'}, {name: 'Server 2', country: 'PL'}, {name: 'Server 3', country: 'US'}, {name: 'Server 4', country: 'DE'}, {name: 'Server 5', country: 'US'}];
const result = _(arr).groupBy(x => x.country)
.map((value, key) => ({country: key, count: value.length}));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
说明:
- 第1步:根据
country
属性 对数组元素进行分组 - 第2步:使用具有2个参数值的.map:
key
是组的名称(国家/地区),value
是对象的数组.
- Step 1: Group the elements of array-based on
country
property - Step 2: Using .map with 2 params value:
key
is the group's name (country),value
is the array of objects.
参考资源:
这篇关于数组中分组项和计数项的简洁方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文