gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 12:12:02 24 4
gpt4 key购买 nike

包括有多少潜在选民年龄在 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
}

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

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

//输出

{
youngVotes: 1 ,
youth: 1 ,
midVotes: 1 ,
mids: 1 ,
oldVotes: 1 ,
olds: 1
}

所需的实际输出:

{
youngVotes: 1,
youth: 4,
midVotes: 3,
mids: 4,
oldVotes: 3,
olds: 4
}

最佳答案

我首先创建一个辅助函数,返回与传递的年龄相对应的属性字符串(例如 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);

关于javascript - 查找对象数组中的计数总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59890923/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com