我想创建一个自定义对象,基于它在数组内部发生的次数
var votes = [
"Clinton","Trump","Clinton","Clinton","Trump","Trump","Trump","None"];
//example of a way to get it with a hardcoded instance
var name= "Trump";
var count = votes.reduce(function(n, val) {
return n + (val === name);
}, 0)
console.log({name: name, votes: count})
//would print {name: trump, votes: 4}
现在,我只用硬编码的名称制作了函数,但我想这样做,这样我也可以检查数组中是否存在多个名称。
我想使用reduce函数来使用它并创建一个自定义对象,包括所有名称和投票