简体   繁体   English

计算JavaScript中多个关联数组中值的出现

[英]Count the occurrence of a value among multiple associative arrays in JavaScript

What is the most optimal way to count the occurrence of a value among many associative arrays. 在许多关联数组中对值的出现进行计数的最佳方法是什么。 For instance, we have 例如,我们有

var array1 = {
  firstname: 'john',
  lastname: 'bob'
};
var array2 = {
  firstname: 'sara',
 lastname: 'johnson'
};
var array 3 = {
  firstname: 'john',
  lastname: 'paul'
};

how would I in this case count the number of times "john" occurs as a first name? 在这种情况下,我如何计算“约翰”作为名字出现的次数? (return value should be 2) (返回值应为2)

To make a count use the function reduce , you don't need to create additional arrays (using the function filter ) for doing that. 要使用reduce函数进行计数,您无需为此创建其他数组(使用function filter )。

 var array1 = {firstname: 'john',lastname: 'bob'}, array2 = {firstname: 'sara',lastname: 'johnson'}, array3 = {firstname: 'john',lastname: 'paul'}, count = [array1, array2, array3].reduce((a, c) => (a + (Object.keys(c).findIndex(k => k === 'firstname' && c[k] === 'john') > -1)), 0); console.log(count); 

Put them into a single larger array, filter it by the john name, and then check its length: 将它们放入一个更大的数组中,用john名称filter ,然后检查其长度:

 const array1 = { firstname: 'john', lastname: 'bob' }; const array2 = { firstname: 'sara', lastname: 'johnson' }; const array3 = { firstname: 'john', lastname: 'paul' }; const input = [array1, array2, array3]; const johnCount = input.filter(({ firstname }) => firstname === 'john').length; console.log(johnCount); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM