gpt4 book ai didi

javascript - 如何根据频率对数组中的键进行排序

转载 作者:行者123 更新时间:2023-12-01 05:36:36 26 4
gpt4 key购买 nike

我的提交按钮终于可以使用了。然而,它并没有计算结果中的所有选票。如何让我的提交按钮对所有投票进行排序?

HTML:

    <!DOCTYPE html>
<html>
<link rel="stylesheet" text="text/css" href="movies.css">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>

<title>
Movie List
</title>
</head>
<body>
<h1>My Favorite Movies</h1>
<div id = "first">
<input type="text" id="movie" placeholder="Movie">
<button id="enter">Enter</button>
</div>
<div id="left">
<div id="list"><u>Chosen Films:</u></div>
<!-- <div>Chosen Films: <span id="list"></span></div> -->
<!-- <div id="films"></div> -->
<div id="best"><u>You're Best Films:</u></div>
<button id="submit">Submit</button>
</div>

<div id= "results"><u>Results</u></div>

<script type="text/javascript" src="movies.js"></script>
</body>
</html>

Javascript:

$(document).ready(function() {
var films = [];
// with working vote button
$("#enter").click(function () {
var movie = $("#movie").val();
var $btn = $('<button />', {
id: "vote",
type: "button",
text: "Vote",
value: movie,
click: function(){
var vote = this.value;
$("#best").append('<p>'+vote+'</p>');
films.push(vote);
}
});

var $p = $('<p />');
$p.append($btn, " ", movie);
$p.appendTo("#list");
});
});

所以问题就出在这里:

此代码应允许提交按钮将“您最好的电影”下列出的电影按照投票顺序排列在“结果”下的第三个列表中。

$("#submit").click(function () {
var ballot = {};
for (var i = 1; i < films.length; i++) {
var key = films[i];
ballot[key] = (ballot[key] || 0) + 1;
}
var elect = [];
for (key in ballot) elect.push({key: key, freq: ballot[key]});
elect.sort(function(a,b){return b.freq - a.freq});
console.log(elect);
for (var i = 0; i < elect.length; i++){
console.log(elect[i].key);
$("#results").append('<p>' + elect[i].key + '</p>');
}
});

如有任何建议或想法,我们将不胜感激!

最佳答案

$("#submit").click(function () {
var ballot = {};
for ( var i = 0; i < films.length; i++) {
var key = films[i];
ballot[key] = (ballot[key] || 0) + 1;
}
var elect = [];
for (key in ballot) elect.push({key: key, freq: ballot[key]});
elect.sort(function(a,b){return b.freq - a.freq});
console.log(elect);
for (var j = 0; j < elect.length; j++){
console.log(elect[j].key);
$("#results").append('<p>' + elect[j].key + '</p>');
}

关于javascript - 如何根据频率对数组中的键进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33616999/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com