计算JavaScript

时间:2018-04-29 01:26:45

标签: javascript arrays associative-array

在许多关联数组中计算值出现的最佳方法是什么。例如,我们有

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

在这种情况下,我将如何计算次数" john"作为名字出现? (返回值应为2)

2 个答案:

答案 0 :(得分:2)

要使用函数reduce进行计数,您不需要创建其他数组(使用函数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);




答案 1 :(得分:1)

将它们放在一个更大的数组filter中,用john名称,然后检查它的长度:



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