查找对象数组中的计数总数

Tha*_*thy 0 javascript

包括有多少潜在选民年龄在 18-25 岁之间,有多少人在 26-35 岁之间,有多少人在 36-55 岁之间,以及每个年龄段有多少人实际投票。包含此数据的结果对象应具有 6 个属性。

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

function voterResults(arr) {
   // your code here
}

console.log(voterResults(voters)); // Returned value shown below:
/*
{ youngVotes: 1,
  youth: 4,
  midVotes: 3,
  mids: 4,
  oldVotes: 3,
  olds: 4 
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试这个特定问题,下面是我尝试过的,我可以在其中形成哈希图。但不知道如何解决上述问题。

function voterResults(arr) {
  let votesArray = ['youngVotes', 'youth', 'midVotes', 'mids', 
      'oldVotes', 'olds']
   return votesArray.reduce((acc, it) => {
     acc[it] = (acc[it] || 0) + 1  
     return acc;
   }, {})
}
Run Code Online (Sandbox Code Playgroud)

//输出

{
   youngVotes: 1 ,
   youth: 1 ,
   midVotes: 1 ,
   mids: 1 ,
   oldVotes: 1 ,
   olds: 1
}
Run Code Online (Sandbox Code Playgroud)

实际需要的输出:

{
  youngVotes: 1,
  youth: 4,
  midVotes: 3,
  mids: 4,
  oldVotes: 3,
  olds: 4 
}
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 6

我首先创建一个辅助函数,它返回与传递的年龄相对应的属性字符串(例如20-> ['youth', 'youngVotes'])。然后使用.reduce迭代数组voters- 调用该函数来找出要递增的属性,然后递增它:

const getCat = (age) => {
  if (age < 25) return ['youth', 'youngVotes'];
  if (age < 35) return ['mids', 'midVotes'];
  return ['olds', 'oldVotes'];
};
var 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}
];

const counts = voters.reduce((a, { age, voted }) => {
  const [prop, voteProp] = getCat(age);
  a[prop] = (a[prop] || 0) + 1;
  if (voted) {
    a[voteProp] = (a[voteProp] || 0) + 1;
  }
  return a;
}, {});
console.log(counts);
Run Code Online (Sandbox Code Playgroud)