目标
我正在尝试制作一个函数,该函数将采用“投票”数组并返回一个对象,该对象包含每个“候选人”获得 1 分的次数。
例如一个数组,例如:
[
{
"blue": 1,
"red": 3,
"purple": 2,
"yellow": 4
},
{
"blue": 2,
"red": 3,
"purple": 4,
"yellow": 1
},
{
"blue": 1,
"red": 2,
"purple": 4,
"yellow": 3
},
{
"blue": 3,
"red": 4,
"purple": 2,
"yellow": 1
}
];
应该返回一个对象
{
"blue": 2,
"red": 0,
"purple": 0,
"yellow": 2
}
当前代码
目前我已经编写了函数
// adds up the first choice results from raw data
// return object containing number of first choice votes each candidate received
const add_first_choices = function (raw_data) {
// create object to store number of first choices
const storage_obj = empty_candidate_obj(raw_data);
// loop through results, adding first choices to storage_obj
raw_data.forEach(function (single_voter_obj) {
Object.values(single_voter_obj).forEach(function (value) {
if (value === 1) {
storage_obj[getKeyByValue(single_voter_obj, value)] += 1;
}
});
});
return storage_obj;
};
它使用以下两个其他功能
// returns object of candidate names, each with value of 0
const empty_candidate_obj = function (raw_data) {
const input_data = raw_data;
let first_vote = input_data[0];
const keys = Object.keys(first_vote);
keys.forEach(function (key) {
first_vote[key] = 0;
});
return first_vote;
};
和
// returns key from object value
const getKeyByValue = function (object, value) {
return Object.keys(object).find((key) => object[key] === value);
};
问题
将上述数组输入我的函数时,它返回
{
blue: 1,
red: 0,
purple: 0,
yellow: 2
}
=> 不像预期的那样!
你知道我做错了什么吗?
感谢您的任何回复:)