本文介绍了数组中分组项和计数项的简洁方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
第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.
我有一个像这样的数组:
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="cdnjs.cloudflare/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="cdnjs.cloudflare/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
说明:
参考资源:
- 使用lodash .groupBy.如何为分组输出添加自己的键?
更多推荐
数组中分组项和计数项的简洁方法
发布评论