JS 依照元素出現數量排序

同樣是最近遇到的狀況,需要利用陣列內元素出現的數量進行排序,以下為範例程式:

var array = ["1", "2", "4", "5", "2", "4", "2", "3"];
var str = array.toString();
var filter = [];
var result = [];
document.write("原始陣列:" + array + "<br>");

var get = function (str, tar, arr, tmp) {
    if (str.indexOf(tar) >= 0) {
        tmp = str.slice(str.indexOf(tar) + 1);
        arr.push(tar);
        get(tmp, tar, arr, tmp);
    }
    return arr;
}

for (i in array) {
    var elm = [];
    var tmp;
    var fstr = filter.join();
    if (fstr.indexOf(array[i]) >= 0) {
        continue;
    } else {
        var tmp_arr = get(str, array[i], elm, tmp);
        result.push(tmp_arr.length + ':' + tmp_arr[0]);
        filter.push(array[i]);
    }
}

result.sort();
result.reverse();

//按照出現次數排序,不刪除重複元素
var finishArray = [];

for (index in result) {
    var show = result[index].split(':');
    for (i = 0; i < show[0]; i++) {
        finishArray.push(show[1]);
    }
}
document.write("按出現次數排序,不刪除重複元素:" + finishArray + "<br>");

//按照出現次數排序,刪除重複元素
var finishArray = [];
for (index in result) {
    var show = result[index].split(':');
    finishArray.push(show[1]);
}
document.write("按出現次數排序,刪除重複元素:" + finishArray + "<br>");

輸出結果:

原始陣列:1,2,4,5,2,4,2,3
按出現次數排序,不刪除重複元素:2,2,2,4,4,5,3,1
按出現次數排序,刪除重複元素:2,4,5,3,1

You may also like...

1,366,604 Responses

  1. My coder is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using Movable-type on various websites for about a year
    and am worried about switching to another platform. I have heard very good things about blogengine.net.
    Is there a way I can transfer all my wordpress content
    into it? Any kind of help would be greatly appreciated!

  2. kasih4d表示:

    Hello just wanted to give you a quick heads up. The text in your article seem
    to be running off the screen in Opera. I’m not sure if this is a format issue or something
    to do with browser compatibility but I thought I’d post to
    let you know. The design and style look great though! Hope you get the problem solved soon. Many thanks

  3. Haas ST 30Y表示:

    My spouse and I stumbled over here by a different web page and thought I
    should check things out. I like what I see so
    now i’m following you. Look forward to checking out your web page repeatedly.

  4. Marcelabelp表示:

    http://mexicoph24.life/# best online pharmacies in mexico

  5. Michaelcew表示:

    http://mexicoph24.life/# purple pharmacy mexico price list

  6. What You Should Be Focusing On Improving Mobility Scooters Near Me For Sale Motorized scooters

  7. best vps表示:

    Howdy this is somewhat of off topic but I was wondering if blogs use
    WYSIWYG editors or if you have to manually code with HTML.
    I’m starting a blog soon but have no coding experience so I wanted to get guidance from someone with experience.

    Any help would be greatly appreciated!

  8. Stevenrip表示:

    india pharmacy: Generic Medicine India to USA – india online pharmacy

  9. Marcelabelp表示:

    http://canadaph24.pro/# canadian online drugstore

  10. Marcelabelp表示:

    http://mexicoph24.life/# mexican mail order pharmacies

  11. Greetings! This is my first comment here so I just wanted to give a quick shout out and tell you I really enjoy reading
    through your posts. Can you recommend any other blogs/websites/forums that cover the same topics?
    Thanks for your time!

  12. jimgodwcob表示:

    Звучит вполне заманчиво
    тесное взаимодействие с вами позволяет нам максимально полно соблюсти все мечтания и условия по написанию качественных работ, https://radiplomas.com установленные в конкретном ВУЗе преподавателем на территории процесса запнятий и программы.

  13. Marcelabelp表示:

    https://canadaph24.pro/# canada pharmacy reviews

  14. 5 Killer Quora Answers To Memory Foam Double Mattresses double mattress

  15. Robby表示:

    The Secret Secrets Of Mobile Automobile Locksmith mobile automobile locksmith near me (Robby)

  16. 10 Wrong Answers To Common What CSGO Cases Have Butterfly Knives
    Questions Do You Know The Right Answers? operation breakout weapon case
    (https://funsilo.date/wiki/Clemensenlutz7116)

  17. I read this paragraph fully concerning the comparison of most up-to-date and preceding technologies, it’s awesome article.

  18. Window Repair表示:

    5 Killer Quora Answers To Window Repairman Window Repair

  19. Curt表示:

    Three Greatest Moments In Double Glazed Units Near Me History replacing windows with double
    glazing – Curt,

  20. Rickysem表示:

    canadian pharmacy 1 internet online drugstore Certified Canadian Pharmacies the canadian drugstore

  21. Don’t Be Enticed By These “Trends” About Become Avon Rep becoming A rep

  22. Marcelabelp表示:

    https://mexicoph24.life/# mexican pharmaceuticals online

  23. 10 Sites To Help You To Become A Proficient In Adhd Treatment For Adults Adhd Treatment Without Medication

  24. Marcelabelp表示:

    https://mexicoph24.life/# mexican pharmacy

  25. 10 Things You’ll Need To Be Aware Of Repair Double Glazed Windows Double glazed window repairs near me

  26. Guide To Black Friday Sofa Sale: The Intermediate Guide For
    Black Friday Sofa Sale black friday sofa Sale

  27. Rickysem表示:

    medicine in mexico pharmacies mexican drugstore online reputable mexican pharmacies online

  28. Rickysem表示:

    mexican mail order pharmacies mexican pharmacy mexico drug stores pharmacies

  29. caffe borbone表示:

    Hi, I do believe your website could possibly be having web
    browser compatibility problems. When I take a look at your website in Safari,
    it looks fine however when opening in IE, it has some
    overlapping issues. I just wanted to provide you with a quick heads
    up! Other than that, wonderful blog!

  30. What’s The Current Job Market For Prada Handbag Nylon Professionals?
    prada handbag nylon

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。