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,238,566 Responses

  1. Nila表示:

    Also visit my blog post; Daycares popular listings – Nila,

  2. Your means of telling all in this post is genuinely nice, all be
    able to easily understand it, Thanks a lot.

  3. Bradleygoath表示:

    amoxicillin 500mg capsule cost Amoxicillin buy online amoxicillin 500mg capsules price

  4. Dereketerm表示:

    priligy maxpharm: buy dapoxetine online – priligy

  5. BrandenSlomy表示:

    average cost of generic prednisone: prednisoneraypharm – can i buy prednisone online without prescription

  6. bitcoin cash表示:

    Hi there, I enjoy reading all of your post. I wanted to write a little
    comment to support you.

  7. Bradleygoath表示:

    buy amoxicillin 500mg online Com Pharm rexall pharmacy amoxicillin 500mg

  8. Link exchange is nothing else except it is simply placing
    the other person’s webpage link on your page at proper place and other person will also do same in support of you.

  9. Тут можно преобрести сейф для хранения оружия оружейный сейф москва

  10. BrandenSlomy表示:

    clomid rx: clomid purchase online rex pharm – how can i get cheap clomid without dr prescription

  11. Bradleygoath表示:

    dapoxetine price buy priligy buy priligy max pharm

  12. StevenNub表示:

    amoxicillin 500 mg cost: Amoxicillin for sale – amoxicillin order online

  13. Uazrlhp表示:

    Как не попасть впросак при покупке диплома колледжа или ПТУ в России

    bepgiadinh.com/kupit-attestat-11-klassov-tsena-v-ivanovo.html

  14. Guide To Accident Claim Lawyers: The Intermediate Guide For Accident Claim Lawyers Accident claim Lawyer

  15. Truly quite a lot of useful info!

  16. Тут можно преобрести сейфы оружейные купить оружейные сейфы и шкафы для охотничьего

  17. Pills information leaflet. Brand names.
    xarope de propranolol
    Best information about pills. Read now.

  18. chữ inox表示:

    I am sure this piece of writing has touched all the internet visitors, its really
    really nice paragraph on building up new weblog.

  19. Узнай все о двустороннее варикоцеле рецидив варикоцеле

  20. Markdob表示:

    Всем привет! Может кто знает, где найтиразные блоги о недвижимости? Сейчас читаю – https://amkhmk.ru

  21. As interpretacoes dos sonhos mais populares dos livros mais populares sobre o sono
    Olhar num espelho num sonho

    [url=https://www.sanatorium19.ru/sayanskaya-blagodat/uslugi-lechenie/item/33-fitoparosauna-po-metodu-praskovi.html]Porque e que sonho com o kvass?[/url] [url=https://www.tarocchigratis.info/jannik-sinner-eliminato/#comment-59]Olhar num espelho num sonho[/url] [url=http://leagues.chanticlair.com/leagues/viewtopic.php?p=146249#146249]Sonho de um gato adormecido[/url] [url=http://www5f.biglobe.ne.jp/%7Ekotohaji/yybbs/yybbs.cgi?list=thread]Com que e que um elefante sonha?[/url] [url=http://cgi3.bekkoame.ne.jp/cgi-bin/user/b112154/cream/yybbs.cgi?list=thread]Porque e que sonho em apanhar damascos?[/url] 717c497

  22. Pretty component of content. I just stumbled upon your weblog
    and in accession capital to assert that I acquire actually enjoyed account
    your weblog posts. Anyway I will be subscribing for your feeds or even I fulfillment you access constantly fast.

  23. Porn Sex表示:

    If you desire to increase your know-how simply keep visiting this web site and be updated with the
    newest news update posted here.

  24. Markdob表示:

    Всем привет! Подскажите, где найтиполезные статьи о недвижимости? Пока нашел – https://amkhmk.ru

發佈留言

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