数组中分组项和计数项的简洁方法

编程入门 行业动态 更新时间:2024-10-27 06:28:47
本文介绍了数组中分组项和计数项的简洁方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个像这样的数组:

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>

说明:

  • 第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.
  • 参考资源:

    • 使用lodash .groupBy.如何为分组输出添加自己的键?

    更多推荐

    数组中分组项和计数项的简洁方法

    本文发布于:2023-11-22 08:39:11,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1616723.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:简洁   组中   方法

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!