计算对象数组中特定属性值的出现 [英] Counting occurrences of particular property value in array of objects

查看:93
本文介绍了计算对象数组中特定属性值的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何计算像这样的对象数组上出现的次数:

I would like to know how i can count the number of occurences on an array of object like this one :

[
{id : 12,
 name : toto,
},
{id : 12,
 name : toto,
},
{id : 42,
 name : tutu,
},
{id : 12,
 name : toto,
},
]

在这种情况下,我希望有一个函数可以给我这个功能:

in this case i would like to have a function who give me this :

getNbOccur(id){
//don't know...//

return occurs;
}

如果我给ID 12,我想拥有3.

and if i give the id 12 i would like to have 3.

我该怎么做?

推荐答案

一个简单的ES6解决方案正在使用

A simple ES6 solution is using filter to get the elements with matching id and, then, get the length of the filtered array:

const array = [
  {id: 12, name: 'toto'},
  {id: 12, name: 'toto'},
  {id: 42, name: 'tutu'},
  {id: 12, name: 'toto'},
];

const id = 12;
const count = array.filter((obj) => obj.id === id).length;

console.log(count);

编辑:另一个更有效的解决方案(因为它不会生成新的数组)是使用:

Edit: Another solution, that is more efficient (since it does not generate a new array), is the usage of reduce as suggested by @YosvelQuintero:

const array = [
  {id: 12, name: 'toto'},
  {id: 12, name: 'toto'},
  {id: 42, name: 'tutu'},
  {id: 12, name: 'toto'},
];

const id = 12;
const count = array.reduce((acc, cur) => cur.id === id ? ++acc : acc, 0);

console.log(count);

这篇关于计算对象数组中特定属性值的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆