JSFiddle - React, Tailwind, and code Playground
JavaScript
const data = [{
"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
}];
console.log(add_first_choices(data));
// adds up the first choice results from raw data
// return object containing number of first choice votes each candidate received
function add_first_choices(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, index) {
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
function empty_candidate_obj(raw_data) {
const input_data = raw_data.map(obj => ({
...obj
}));
let first_vote = input_data[0];
const keys = Object.keys(first_vote);
keys.forEach(function(key) {
first_vote[key] = 0;
});
// console.log(raw_data)
return first_vote;
};
// returns key from object value
function getKeyByValue(object, value) {
return Object.keys(object).find((key) => object[key] === value);
}