HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Find the election winner

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
electionthewinnerfind

Problem

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){
        if(vObj[name] > maxVotes){
            maxVotes = vObj[name];
            winners = [name];
        }
        else if (vObj[name] === maxVotes){
            winners.push(name);
        }
    }

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

Solution

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

Code Snippets

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

Context

StackExchange Code Review Q#148918, answer score: 2

Revisions (0)

No revisions yet.