且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

计算对象数组中特定属性值的出现次数

更新时间:2022-12-10 10:03:20

一个简单的 ES6 解决方案是使用 filter 获取匹配 id 的元素,然后获取过滤后数组的长度:

const array = [{id: 12, name: 'toto'},{id: 12, name: 'toto'},{id: 42, name: 'tutu'},{id: 12, name: 'toto'},];常量 ID = 12;const count = array.filter((obj) => obj.id === id).length;console.log(count);

编辑:另一种更有效的解决方案(因为它不生成新数组)是使用 reduce 作为 @YosvelQuintero 建议:

const array = [{id: 12, name: 'toto'},{id: 12, name: 'toto'},{id: 42, name: 'tutu'},{id: 12, name: 'toto'},];常量 ID = 12;const count = array.reduce((acc, cur) => cur.id === id ? ++acc : acc, 0);console.log(count);

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;
}

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

How can i do that?

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);