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

时间:2015-11-09 19:46:24

标签: javascript jquery

我的提交按钮终于有效了。但是,它不计算结果中的所有投票。如何获取提交按钮以对所有投票进行排序?

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

任何建议或想法都将不胜感激!

1 个答案:

答案 0 :(得分:0)

$("#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>');
    }