My current code seems to be quite bloated and I believe it can be optimized for better efficiency. The goal is to compare an array of objects that represent players, in order to determine the player with the highest majorityScore property. In cases where there are multiple players with the same high score, a comparison of their factions using a priorityMap will determine the ultimate winner.
players = [
{
majorityScore: 4,
faction: 'AR'
},
{
majorityScore: 8,
faction: 'MOU'
},
{
majorityScore: 2,
faction: 'MOB'
},
{
majorityScore: 8,
faction: 'I'
}
];
const priorityMap = {
'MOB': 1,
'I': 2,
'MOU': 3,
'AR': 4,
'S' : 0
}
let winner;
let highScore = -1;
let duplicates = [];
for(let i = 0; i < players.length; i++){
if(players[i].majorityScore > highScore){
highScore = players[i].majorityScore;
winner = players[i]
duplicates = [winner];
} else if (players[i].majorityScore === highScore){
duplicates.push(players[i]);
};
}
if(duplicates.length > 1){
let highFactionScore = duplicates.reduce((a,v) => {
if(priorityMap[v.faction] > a){
a = priorityMap[v.faction];
}
return a;
}, 0);
let winningFaction = Object.keys(priorityMap).find((k) => {
return priorityMap[k] === highFactionScore;
});
winner = duplicates.filter((v) => {
return v.faction === winningFaction
})
}