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,404,130 Responses

  1. Collin表示:

    They have items to offer or services to offer.

    Feel free to visit my web blog :: replacement windows
    in waco texas (Collin)

  2. Bookmarks表示:

    About Our Vehicle Mishap Lawyers Ratings.

    Feel free to visit my web site … Bookmarks

  3. Bookmarks表示:

    60+ spectacular examples of geometric styles.

    my web-site … Bookmarks

  4. They have products to offer or solutions to use.

    My web site Can a foundation Apply for grants

  5. Bookmarks表示:

    40 Examples of Bonus Cool TShirt Designs Lava360.

    my web-site :: Bookmarks

  6. Charlesrab表示:

    Viagra pas cher livraison rapide france viagra sans ordonnance Viagra sans ordonnance 24h suisse

  7. HeathZex表示:

    pharmacie en ligne france livraison internationale: Pharmacies en ligne certifiees – pharmacie en ligne fiable

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

  9. 15 Astonishing Facts About Sash Window Repair window Repairs

  10. HeathZex表示:

    Pharmacie sans ordonnance: Medicaments en ligne livres en 24h – pharmacie en ligne sans ordonnance

  11. What i don’t realize is in fact how you are no longer really a lot more neatly-liked than you may be right now.
    You’re very intelligent. You realize thus significantly in the case of this subject, made
    me personally imagine it from a lot of numerous angles. Its like women and
    men aren’t fascinated unless it’s one thing to do with Woman gaga!
    Your own stuffs nice. All the time maintain it up!

  12. HeathZex表示:

    Achat mГ©dicament en ligne fiable: Cialis sans ordonnance 24h – Pharmacie Internationale en ligne

  13. Bookmarks表示:

    Genuine HGH Advantages (NewULife Hgh Gel Not Checked
    Yet).

    Here is my blog post … Bookmarks

  14. USP human growth hormonal agent (somatropin).

    my page; nib not working

  15. What is New U Life SOMADERM Transdermal Gel.

    Feel free to surf to my homepage: Nib Makeup Foundation

  16. USP human development hormone (somatropin).

    Here is my website: vigabatrin trade name

  17. There are several locations to discover tee t shirt design app for ipad designs.

  18. I’m not that much of a internet reader to be honest but your sites really nice, keep it up!
    I’ll go ahead and bookmark your website to come back later.
    Cheers

    Feel free to visit my site; เครดิตฟรี38บาท

  19. WalterShexy表示:

    Обмены электронных валют мгновенны. Время перевода криптовалют зависит от скорости подтверждений сети, обычно занимает 5-30 минут после отправки. В случае загруженности сети блокчейн, данное время может увеличится paypal to usdt trc20

  20. Britt表示:

    Developers from all over the world pitch you concepts.

    Here is my web blog :: Bookmarks [Britt]

  21. Bookmarks表示:

    NewULife Ranks. Welcome to my NewUlife Review.

    Take a look at my homepage – Bookmarks

  22. HeathZex表示:

    acheter mГ©dicament en ligne sans ordonnance: Cialis prix en pharmacie – pharmacie en ligne avec ordonnance

  23. Report the crash to your insurance company.

    Also visit my web blog … truck accident attorney los angeles cz.law

  24. In this case, the life insurance policy firm’s money.

    Also visit my web-site – nib makeup foundation

  25. Bookmarks表示:

    USP human development hormonal agent (somatropin).

    Also visit my homepage: Bookmarks

  26. Upvc Window Repairs Near Me Tools To Streamline Your Everyday Lifethe Only Upvc
    Window Repairs Near Me Trick Every Person Should Learn upvc window Repairs Near me

  27. Сервисный центр предлагает качественый ремонт мфу ricoh мастер по ремонту мфу ricoh

  28. Johnnymet表示:

    Latest medication news. Medicine overview available.
    buy valtrex uk online
    Abuse effects detailed. Pill essentials explained.

發佈留言

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