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,448,017 Responses

  1. FalloGurn表示:

    Хотите делать ставки в любое время и в любом месте – скачайте мостбет мобильное приложение и получите доступ к удобному и функциональному интерфейсу для онлайн-ставок.

  2. I always spent my half an hour to read this weblog’s
    posts everyday along with a cup of coffee.

  3. CurtisBam表示:

    Mexican Easy Pharm: Mexican Easy Pharm – mexican border pharmacies shipping to usa

  4. AndreDib表示:

    canadian pharmacy prices https://indiancertpharm.com/# indian pharmacy
    indian pharmacy

  5. kypit 1s_nfor表示:

    купить программу 1с бухгалтерия http://www.svstrazh.forum24.ru/?1-3-0-00000323-000-0-0-1737110513 .

  6. CurtisBam表示:

    Online medicine: Best Indian pharmacy – indian pharmacy

  7. AlvinJexia表示:

    Эта статья сочетает познавательный и занимательный контент, что делает ее идеальной для любителей глубоких исследований. Мы рассмотрим увлекательные аспекты различных тем и предоставим вам новые знания, которые могут оказаться полезными в будущем.
    Получить дополнительную информацию – https://nakroklinikatest.ru/

  8. Brandonnot表示:

    safe online pharmacies in canada: CanadianMdPharm – canadian pharmacy tampa

  9. gocengqq表示:

    Hello there, I discovered your website by means of Google at the same time as looking for a related subject, your web site
    got here up, it appears to be like good. I’ve bookmarked it in my google bookmarks.

    Hi there, just become alert to your blog through Google,
    and located that it is truly informative. I’m going to be
    careful for brussels. I will be grateful should you proceed
    this in future. A lot of other people shall be benefited from your writing.
    Cheers!

  10. CurtisBam表示:

    canadian compounding pharmacy: Canadian Md Pharm – canadian drugs online

  11. minimum age for doxycycline buy doxycycline 100mg uk where to buy cheap doxycycline
    where can i buy cheap doxycycline without a prescription can i order doxycycline online doxycycline hyclate for malaria
    order cheap doxycycline online
    buy doxycycline pills for sale buy antibiotics doxycycline mexico cost generic doxycycline prices
    buy doxycycline 20 mg online doxycycline hyclate tablets usp 100mg where to get doxycycline no prescription

  12. CurtisBam表示:

    Online pharmacy: Best online Indian pharmacy – Indian Cert Pharm

  13. вывод из запоя стационар [url=http://vyvod-iz-zapoya-v-stacionare-voronezh23.ru/]вывод из запоя стационар[/url] .

  14. AndreDib表示:

    recommended canadian pharmacies https://canadianmdpharm.online/# canada rx pharmacy world
    best online pharmacy india

  15. Brandonnot表示:

    canadian pharmacy 365: canadian pharmacy world – canadian mail order pharmacy

  16. AndreDib表示:

    canadian pharmacy 24 com https://mexicaneasypharm.com/# mexican online pharmacies prescription drugs
    mail order pharmacy india

  17. Brandonnot表示:

    Mexican Easy Pharm: mexican border pharmacies shipping to usa – Mexican Easy Pharm

  18. kypit 1s_joor表示:

    настроить 1с бухгалтерия цена настроить 1с бухгалтерия цена .

  19. Richardker表示:

    не работает
    _________________
    Free casino online

  20. agen slot777表示:

    I am extremely inspired along with your writing talents as well as
    with the structure on your weblog. Is that this a paid theme or did you customize
    it yourself? Anyway stay up the nice quality writing, it is uncommon to peer
    a great weblog like this one these days..

  21. AndreDib表示:

    best online canadian pharmacy https://canadianmdpharm.com/# canadian pharmacy no scripts
    top online pharmacy india

  22. kypit 1s_fbEn表示:

    настроить 1с бухгалтерия цена настроить 1с бухгалтерия цена .

  23. CurtisBam表示:

    pharmacy rx world canada: canada cloud pharmacy – canada drug pharmacy

  24. CurtisBam表示:

    medication from mexico pharmacy: Mexican Easy Pharm – buying prescription drugs in mexico

  25. AndreDib表示:

    canadian pharmacy 365 https://mexicaneasypharm.com/# medication from mexico pharmacy
    top 10 online pharmacy in india

  26. Daniella表示:

    The 9 Things Your Parents Teach You About Leather Couch With Chaise leather couch with chaise (Daniella)

  27. AndreDib表示:

    pharmacy rx world canada https://indiancertpharm.com/# Indian Cert Pharm
    pharmacy website india

發佈留言

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