Find the election winner

Challenge

There are n citizens voting in this year's HackLand election. Each voter writes the name of their chosen candidate on a ballot and places it in a ballot box. The candidate with the highest number of votes wins the election; if two or more candidates have the same number of votes, then the tied candidates' names are ordered alphabetically and the last name wins.

Complete the electionWinner function in your editor. It has 1 parameter: an array of strings, votes, describing the votes in the ballot box. This function must review these votes and return a string representing the name of the winning candidate.

My Code

function electionWinner(votes) {
const vObj = {};
for(let v of votes){
vObj[v] = (vObj[v] || 0) + 1;
}

let winners = [];
let maxVotes = 0;

for(let name in vObj){
winners = [name];
}
else if (vObj[name] === maxVotes){
winners.push(name);
}
}

if(winners.length === 1){
return winners[0];
}
winners.sort();
return winners[winners.length - 1];
}


You can write this simpler:

if(winners.length === 1){
return winners[0];
}
winners.sort();
return winners[winners.length - 1];


Like this:

winners.sort();
return winners[winners.length - 1];


Because if winner contains one element, winners.sort() will do nothing anyway.

vObj is a poor name for a map of vote counts per name.

It could be a good idea to decompose the implementation to smaller functions with a single responsibility:

• Build a map of vote counts
• Find winners
• Find the single winner

Sorting has worse runtime complexity (O(n log n)) than the search for a minimum/maximum (O(n)). For small n that doesn't matter much but once you have tens of thousands of candidates tied for first place it should become noticeable.

Unfortunately Math.max.apply(null, winners) only works if candidate names are numeric but we can come up with another short solution:

return winners.reduce(function(a, b) { return (a >= b) ? a : b; });