简体   繁体   English

返回最大值或等于javascript

[英]Return highest value or equal values javascript

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: 我可以使用以下代码通过obj2示例实现此目的:

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). 当我在obj1示例上使用上面的代码时,我得到的是'kfc',我想要的是'kfc','Pret','Mcds'(无特定顺序)。

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); 

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. 新变量将以数组形式列出“优胜者”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM