为每个出现在javascript数组中的名称制作自定义对象

时间:2018-12-22 22:41:42

标签: javascript closures reduce

我想创建一个自定义对象,基于它在数组内部发生的次数

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函数来使用它并创建一个自定义对象,包括所有名称和投票

0 个答案:

没有答案