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,630,403 Responses

  1. Medicament information. Short-Term Effects.
    where buy cytotec
    All news about medicament. Get now.

  2. Mediabola表示:

    Hi there this is kinda of off topic but I was wanting to know if blogs use
    WYSIWYG editors or if you have to manually code with HTML.
    I’m starting a blog soon but have no coding expertise so
    I wanted to get guidance from someone with experience.
    Any help would be greatly appreciated!

  3. StevenNub表示:

    dapoxetine price: priligy – priligy

  4. Danieljek表示:

    can you buy amoxicillin over the counter in canada https://clomidrexpharm.com/# where can i buy clomid

  5. Узнай все о варикоцеле яичка у мужчины варикоцеле у мужчин

  6. เขียนได้น่าสนใจและไม่ซับซ้อนเกินไปค่ะ

  7. StevenNub表示:

    prednisone tablet 100 mg: Prednisone Without Prescription – prednisone for sale no prescription

  8. I do trust all of the ideas you have presented in your post.
    They are very convincing and can certainly work. Nonetheless, the posts
    are very short for starters. May you please prolong them a bit from subsequent time?
    Thank you for the post.

  9. BrandenSlomy表示:

    amoxicillin 500mg buy online uk: Com Pharm – buy amoxicillin without prescription

  10. StevenNub表示:

    prednisone in uk: raypharm – prednisone 20mg

  11. discover this表示:

    It’s amazing to pay a visit this site and reading the views of all colleagues about
    this article, while I am also zealous of getting knowledge.

  12. StevenNub表示:

    prednisone 20mg price in india: prednisoneraypharm – prednisone canada pharmacy

  13. Dereketerm表示:

    amoxicillin online canada: com pharm – canadian pharmacy amoxicillin

  14. Hänvisningsbonusarna belönar både personen som rekommenderar det specifika casinot
    utan spellicens, och personen som blir hänvisad.

  15. Bosdeal 88表示:

    Hello, I read your blog regularly. Your writing style is witty, keep doing what you’re doing!

  16. Bradleygoath表示:

    875 mg amoxicillin cost Amoxicillin buy online amoxicillin 500mg prescription

  17. Bradleygoath表示:

    purchase amoxicillin online buy amoxil online order amoxicillin 500mg

  18. StevenNub表示:

    buy priligy max pharm: cheap priligy – buy priligy max pharm

  19. It is perfect time to make some plans for the future and
    it’s time to be happy. I have read this post and if I could I desire
    to suggest you some interesting things or tips. Perhaps you
    can write next articles referring to this article. I wish to
    read even more things about it!

  20. ambermotrify表示:

    Извиняюсь, но этот вариант мне не подходит. Может, есть ещё варианты?
    присутствуя в категории знакомства для геев, вы подтверждаете, что для вас не один десяток лет и вы прочли, вебкам модель на дому поняли и пришли к выводу с условиями соглашения о публикации фотографий и соглашения о предоставлении услуг!

  21. Bradleygoath表示:

    order prednisone online canada raypharm prednisone pill prices

  22. walmart black friday deals 2024

    Hi! I could have sworn I’ve been to this website before but after checking through some of the post I realized
    it’s new to me. Anyhow, I’m definitely happy I found
    it and I’ll be bookmarking and checking back frequently!

  23. Узнай все о варикоцеле диагностика варикоцеле 2 степени

  24. Узнай все о варикоцеле причины варикоцеле у мужчин

  25. Thanks for your personal marvelous posting! I definitely enjoyed reading it,
    you might be a great author.I will remember to bookmark your blog
    and may come back sometime soon. I want to encourage
    you to definitely continue your great writing, have a nice
    afternoon!

  26. BrandenSlomy表示:

    can you buy prednisone without a prescription: prednisoneraypharm – prednisone pack

發佈回覆給「варикоцеле у мужчин」的留言 取消回覆

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