• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

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

用户头像
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. 第1步:根据 country 属性
  2. 对数组元素进行分组
  3. 第2步:使用具有2个参数值的.map: key 是组的名称(国家/地区), value 是对象的数组.
  1. Step 1: Group the elements of array-based on country property
  2. 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
系列文章
更多 icon
同类精品
更多 icon
继续加载