数组分组项和计数项的简洁方法
it1352
帮助1人
问题说明
我有一个像这样的数组:
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.
正确答案
#1
万岁!!!
最近几天研究之后,我终于像这样使用 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.
参考资源:
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcebffb
系列文章
更多
同类精品
更多
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20