Javascript 使用array.reduce统计对象数组中的发生次数

Javascript 使用array.reduce统计对象数组中的发生次数,javascript,arrays,Javascript,Arrays,我有这样一群选民: let voters = [ {name:'Bob' , age: 30, voted: true}, {name:'Jake' , age: 32, voted: true}, {name:'Kate' , age: 25, voted: false}, {name:'Sam' , age: 20, voted: false}, {name:'Phil' , age: 21, voted: true}, {name:'Ed'

我有这样一群选民:

let voters = [
    {name:'Bob' , age: 30, voted: true},
    {name:'Jake' , age: 32, voted: true},
    {name:'Kate' , age: 25, voted: false},
    {name:'Sam' , age: 20, voted: false},
    {name:'Phil' , age: 21, voted: true},
    {name:'Ed' , age:55, voted:true},
    {name:'Tami' , age: 54, voted:true},
    {name: 'Mary', age: 31, voted: false},
    {name: 'Becky', age: 43, voted: false},
    {name: 'Joey', age: 41, voted: true},
    {name: 'Jeff', age: 30, voted: true},
    {name: 'Zack', age: 19, voted: false}
];
我需要计算有多少人投票(
true

我可以使用for循环找到它,但我正在学习
reduce
方法,我想在这里应用它,但似乎不知道如何使用

// works perfectly
function totalVotes(voters){
      let total = 0;
      for (i=0; i < voters.length; i++){
        if (voters[i].voted === true) {
          total++
        }
      }
      return total
    }

您可以将累加器的初始值设置为
0
,如果当前元素的
voted
属性为true,则向其添加1,否则添加
0

让投票人=[
{姓名:'Bob',年龄:30岁,投票结果:正确},
{姓名:'Jake',年龄:32岁,投票结果:正确},
{姓名:'Kate',年龄:25岁,投票:false},
{姓名:'Sam',年龄:20岁,投票:false},
{姓名:'Phil',年龄:21岁,投票结果:正确},
{姓名:'Ed',年龄:55岁,投票结果:正确},
{姓名:'Tami',年龄:54岁,投票结果:正确},
{姓名:'Mary',年龄:31岁,投票:false},
{姓名:'Becky',年龄:43岁,投票:false},
{姓名:'Joey',年龄:41岁,投票结果:正确},
{姓名:'Jeff',年龄:30岁,投票结果:正确},
{姓名:'Zack',年龄:19岁,投票:false}
];
让res=选民。减少((acc,{voted})=>acc+(投票?1:0),0);

控制台日志(res)亲爱的@hev1,谢谢!这是可行的,但现在我不明白{voted}是如何获取KVP的值的。你能帮我弄清楚吗?我刚刚用了{age},累加器设为零,它把所有年龄加起来,就像预期的那样。但是我仍然不明白{age}怎么能选择年龄的值:numberrit是一个谢谢@莱昂纳多·布雷吉诺没问题。这回答了你的问题吗?
function totalVotes2(voters){
      voters.reduce(function (contador, item){
        if (item.voted === true){
          console.log(item)
          console.log(contador)
          //cant figure out how to make it count
          }
          // and how to return it
      }, 0)
    }