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,982 Responses

  1. HeathZex表示:

    pharmacie en ligne france livraison internationale: cialis sans ordonnance – Pharmacie sans ordonnance

  2. A Look Into The Future How Will The ADHD Test For Women Industry Look Like In 10 Years?
    adhd in Women checklist

  3. Charlesrab表示:

    Viagra 100mg prix Meilleur Viagra sans ordonnance 24h Viagra Pfizer sans ordonnance

  4. drigana表示:

    Hi there, just wanted to mention, I enjoyed this blog post.
    It was helpful. Keep on posting!

  5. This is a topic which is close to my heart… Thank you!

    Where are your contact details though?

  6. Charlesrab表示:

    pharmacie en ligne cialis prix pharmacie en ligne sans ordonnance

  7. HeathZex表示:

    trouver un mГ©dicament en pharmacie: Pharmacie sans ordonnance – pharmacie en ligne france livraison belgique

  8. 1x벳은 스포츠 베팅과 카지노 게임의 균형이 잘 잡힌 사이트로, 한국 플레이어들에게 최적화된 플랫폼을 제공합니다. 다양한 게임과 프로모션이 꾸준히 업데이트되며, 여러 결제 수단을 지원해 빠르고 안전한 게임 경험을 제공합니다.

  9. HeathZex表示:

    pharmacie en ligne sans ordonnance: Cialis sans ordonnance 24h – acheter mГ©dicament en ligne sans ordonnance

  10. KHB855表示:

    Incredible! This blog looks exactly like my old one!
    It’s on a totally different subject but it has pretty much the same layout and design. Wonderful choice
    of colors!

  11. HeathZex表示:

    pharmacie en ligne: Cialis sans ordonnance 24h – pharmacie en ligne pas cher

  12. Stephengen表示:

    http://clssansordonnance.icu/# pharmacie en ligne pas cher

  13. Bit Maxair表示:

    Aw, this was an extremely nice post. Spending some time and actual effort to generate a
    very good article… but what can I say… I procrastinate a whole lot and don’t seem to
    get nearly anything done.

  14. Stephengen表示:

    http://clssansordonnance.icu/# pharmacie en ligne pas cher

  15. Сервисный центр предлагает мастерские ремонта пнв veber мастерские ремонта пнв veber

  16. Jamesses表示:

    Познакомьтесь маленький нашим проф коллективом, который строит уникальную мебель, воплощая ваши мечтания в явь https://www.cehitae2kuhnishki.ru/.

  17. Stephengen表示:

    https://vgrsansordonnance.com/# Viagra 100mg prix

  18. Medication prescribing information. What side effects can this medication cause?
    can i order generic priligy no prescription
    Everything what you want to know about medicine. Read information here.

  19. Charlesrab表示:

    vente de mГ©dicament en ligne pharmacie en ligne sans ordonnance pharmacie en ligne france fiable

  20. Профессиональный сервисный центр по ремонту МФУ в Москве.
    Мы предлагаем: сервис по ремонту мфу
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  21. JamesBuice表示:

    mexican mail order pharmacies: mexican pharma – mexican mail order pharmacies
    mexican mail order pharmacies

  22. anotepad.com表示:

    Save Funds In Your Business 주소모음 (anotepad.com)

  23. Hello! This is kind of off topic but I need some advice from an established blog.
    Is it very difficult to set up your own blog? I’m not very techincal but
    I can figure things out pretty quick. I’m thinking about setting up my
    own but I’m not sure where to begin. Do you have any tips or suggestions?
    With thanks

    Here is my webpage: the billionaire brain wave

  24. HeathZex表示:

    acheter mГ©dicament en ligne sans ordonnance: Cialis sans ordonnance pas cher – Pharmacie en ligne livraison Europe

  25. If your skle purpose is heaart training, Mio makes a
    speciality of heart training watches and bands, and has additionally acquired quite a
    few awatds onn this phase.

    Here is my blog post: kaเกมยิงปลา

  26. HeathZex表示:

    pharmacie en ligne france pas cher: pharmacie en ligne france livraison internationale – Pharmacie sans ordonnance

發佈留言

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