按重复次数按字母顺序排序HTML“LI”

时间:2014-05-19 05:05:28

标签: javascript html sorting

问题:如何通过遵循规则

订购HTML标签(" LI")

规则

  1. 从有序&#34开始;重复时间" :li(DESC)
  2. 然后按字母顺序排列
  3. 我想订购HTML标签(" LI")

    1. 我会将HTML标签(" Li")放入数组(确定)
    2. 按规则排序数组(不行)
    3. 回到html(ok)
    4. 例如

      输入

       
        put "li" into "array" 
      [R,What,JIMMY,O,The,News,Fusion,JIMMY,Sc,What,AgentsOfShield,WABCE,Black,Alad,The,2020,JIMMY,News,Dancing,Fusion,Fusion,R,What,JIMMY,O,The,News,Fusion]
        
      

      output (order should be like this)

       
          [Fusion, JIMMY, News, The, What, O, R, 2020, AgentsOfShield, Alad,Black,Dancing,Sc ,WABCE ,Fusion ,JIMMY ,News ,The ,What ,O ,R ,Fusion ,JIMMY ,News ,The ,What ,Fusion ,JIMMY]
       
      

      However,the output order is wrong in my code . wrong output

       
      [Fusion, JIMMY, What, The, Fusion, JIMMY, News, What, News, O, JIMMY, The, R, Fusion, The, AgentsOfShield, O, JIMMY, R, Fusion, Sc, News, Dancing, Black, WABCE, What, Alad, 2020]
       
      

      Please check the codehttp://jsfiddle.net/BrianHCM/9CVHx/5/

      谢谢!

1 个答案:

答案 0 :(得分:0)

这里是更新后的代码,它会显示其订单计数的唯一字词。我留下了一条评论,说明你可以在哪里重复原来的李的重复但是有序而不是独特的。

希望得到这个帮助。

function Randomize() {
    var ul = document.querySelector('#editor_0_ddList_0');
        lis = ul.querySelectorAll('li'),
        words = {},
        result = [];

    //Get the words and counts
    for(var i = 0; i < lis.length; i++){
        var li = lis[i],
            name = li.innerHTML;

        //Set some data of the word with the founded LI's
        if(words[name] == null){ //Create the object
            words[name] = {
                word : name,
                lis : [li],
                count : 1
            };
        }else{ //Update
            words[name].lis.push(li);
            words[name].count++;
        }

        //Clean the li
        li.parentNode.removeChild(li);
    }

    //Set the result array with the words and datas
    for(var word in words) result.push(words[word]);

    //Sort all
    result.sort(function (a, b){
        return (a.count > b.count) ? -1 : 
        (a.count == b.count ) ? a.name > b.name ? -1 : 1 : 1;
    });

    //Append ordered
    for(var r = 0; r < result.length; r++){
        var li = document.createElement('LI');
        li.innerHTML = result[r].word + ' x' + result[r].count;

        //Make a for of result[r].lis and append to UL if you want to use the originals and repeated LI's

        ul.appendChild(li);
    }
 }