0

I'm creating a voting system and I have the following object:

var obj1 = { Mcds: 2, Pret: 2, kfc: 2, BK: 1 }

or (depending on the votes) it could be:

var obj2 = { Mcds: 2, Pret: 2, BK: 3 }

What I want is to display the most voted restaurant or restaurants.

I can achieve this with the obj2 example using the following code:

var obj2Keys = Object.keys(obj2);

var mostVoted = obj2Keys.reduce(function(previousValue, currentValue){
    return obj2[previousValue] > obj2[currentValue] ? previousValue : currentValue;
}); // returns 'BK'

When I use the above code on the obj1 example I get 'kfc' what I want is 'kfc' 'Pret' 'Mcds' (in no particular order).

2 Answers 2

1

You need to accumulate all the winning names into an array. When you get a tie for the high vote, you add the element to the array; when you get a higher vote, you start a new array.

var obj1 = {
  Mcds: 2,
  Pret: 2,
  kfc: 2,
  BK: 1
}

var high_vote = 0;
var winners;
for (var key in obj1) {
  if (obj1.hasOwnProperty(key)) {
    if (obj1[key] > high_vote) {
      winners = [key];
      high_vote = obj1[key];
    } else if (obj1[key] == high_vote) {
      winners.push(key);
    }
  }
}

alert(winners);

Sign up to request clarification or add additional context in comments.

2 Comments

"most voted restaurant or restaurants", so if you have {Mcds: 2, Pret: 3, BK: 3} you espect to have 2 winners. your code is returning the last winner found.
I forgot to update high_vote in the if. Now it works.
0

Add this below your existing code:

var mostVotedArray = obj2Keys.filter(function(currentValue){
    return obj2[currentValue] == obj2[mostVoted];
});

The new variable will list the "winners" as an array.

3 Comments

You need to do a first pass to set mostVoted.
That's what I said "add this below your existing code"
In his code, mostVoted is a key, not a value. So it should be == obj2[mostVoted].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.