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,129,622 Responses

  1. Drstobeese表示:

    testosterone cypionate online pharmacy: lorazepam indian pharmacy – azithromycin online pharmacy no prescription

  2. The larger Slim battery, excellent for longer runtimes.

    Check out my web-site :: gen2 foil drive assist max

  3. XYGENYX, a licensing firm for FDA-registered products.

    Here is my webpage; texas ranch wedding venues

  4. Easydrorbix表示:

    cytotec online pharmacy: viagra generic pharmacy – global pharmacy viagra

  5. Bookmarks表示:

    In this situation, the life insurance policy business’s cash.

    Also visit my web page – Bookmarks

  6. Bookmarks表示:

    Let me reveal you in my evaluation of NewULife.

    Also visit my page – Bookmarks

  7. A child can have as numerous as 100 convulsions
    a day.

    Also visit my webpage :: at what age do infantile spasms start

  8. Полезные советы по предотвращению дубликатов номеров, как не допустить дублирования номеров при работе с документами, лучшие методы избежания дублирования номеров. Продвинутые методы предотвращения дубликатов номеров, лучшие практики по устранению дубликатов номеров. Как избежать дубликатов номеров в офисе, шифрование номеров: как избежать дубликатов. лучшие способы избежания дубликатов номеров, как предотвратить дублирующиеся номера на документах.
    дубликаты номеров дубликаты номеров .

  9. Drstobeese表示:

    india online pharmacy: phuket pharmacy viagra – viagra in indian pharmacy

  10. Portable vaporizers make use of batteries as a
    power source.

    My blog: plant based vape uk

  11. QMR Дизайн человека https://humandesignplanet.ru Дизайн человека. 1/3 Дизайн человека.

  12. Let me reveal you in my evaluation of NewULife.

    my blog: custom vinyl windows albuquerque

  13. Bookmarks表示:

    USP human growth hormonal agent (somatropin).

    Here is my site – Bookmarks

  14. The intelligence is the best dry herb vape I have attempted.

    Feel free to visit my homepage; plant based meat alternatives uk

  15. 5 Killer Quora Answers On Gorenje Fridge Freezer Retro fridge freezer Retro

  16. Drstobeese表示:

    mexican online pharmacy percocet: ciprofloxacin pharmacy – flovent online pharmacy

  17. Bookmarks表示:

    In this situation, the life insurance policy business’s loan.

    Feel free to visit my web blog Bookmarks

  18. A child can have as numerous as 100 convulsions a day.

    Review my web blog: do infantile spasms happen while sleeping

  19. Drstobeese表示:

    cialis online from us pharmacy: metoprolol people’s pharmacy – online pharmacy greece

  20. Easydrorbix表示:

    pharmacy assistant certification online: bactrim pharmacy – no prescription viagra online pharmacy

  21. These are actually great ideas in on the topic of blogging.

    You have touched some pleasant factors here. Any way keep up wrinting.

  22. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically
    tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some
    time and was hoping maybe you would have some experience with something
    like this. Please let me know if you run into anything.
    I truly enjoy reading your blog and I look forward to
    your new updates.

  23. What is New U Life SOMADERM Transdermal Gel.

    Here is my page; european auto repair shop near me

  24. I’m gone to tell my little brother, that he should also pay a quick
    visit this website on regular basis to obtain updated from newest
    news.

  25. What a information of un-ambiguity and preserveness of valuable know-how regarding unexpected feelings.

  26. What is New U Life SOMADERM Transdermal Gel.

    Also visit my web page – ceramic pot painting near me

  27. Hi, this weekend is nice designed for me, for the reason that this moment i am reading this enormous informative paragraph here at my residence.

  28. Если вы искали где отремонтировать сломаную технику, обратите внимание – профи ремонт

發佈留言

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