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,229,109 Responses

  1. Stephensoobe表示:

    Ни одно застолье невозможно представить себе без освежающих безалкогольных напитков. Сейчас вам не придется тратить свое время и силы на то, чтобы ездить в магазины и покупать соки, минеральную воду доставка алкоголя москва alcotaxi57 online

  2. 10 Reasons You’ll Need To Be Aware Of High Wycombe Windows high wycombe Double glazing –
    glamorouslengths.com

  3. Remarkable things here. I’m very glad to look your article.
    Thanks a lot and I’m looking ahead to touch you. Will you please
    drop me a mail?

  4. Five Killer Quora Answers To Composite Door Hinge Replacement Composite Door hinge replacement

  5. LarryCoell表示:

    deneme bonusu veren siteler betturkey deneme bonusu veren siteler betturkey deneme bonusu veren siteler yeni

  6. Lavonda表示:

    10 Private ADHD Diagnosis UK Tricks All Experts Recommend private adhd assessment york – Lavonda,

  7. Тут можно преобрести сейф шкаф купить оружейные сейфы и шкафы

  8. Good blog post. I absolutely appreciate this website.
    Stick with it!

  9. bokep jepang表示:

    Howdy would you mind sharing which blog platform you’re working with?

    I’m going to start my own blog in the near future but I’m having a tough
    time choosing between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design seems different then most blogs and
    I’m looking for something unique.
    P.S Sorry for getting off-topic but I had to ask!

  10. Could Window Repair Near Be The Key For 2023’s Challenges?
    window repair near Me

  11. Тут можно преобрести несгораемые сейфы сейф пожаростойкий

  12. aiporn.party表示:

    I really like your blog.. very nice colors & theme. Did you design this website yourself or did you hire someone to do it for you?
    Plz respond as I’m looking to design my own blog and would like to know where u got this
    from. many thanks

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

  14. A Step-By-Step Guide To Selecting The Right Windows And Doors Luton glass Repair near me

  15. My parents gave me a purity ring the following year.ラブドール av Even though I knew that they had lived together for several years before getting married,

  16. ClydePab表示:

    Deneme Bonusu Veren Siteler: Deneme Bonusu Veren Siteler – Deneme Bonusu Veren Siteler

  17. The Main Problem With Sports Toto Latest Results And How You Can Solve It 스포츠토토

  18. Aw, this was a really good post. Taking a few minutes and actual effort
    to make a superb article… but what can I say… I put things off a
    whole lot and never seem to get anything done.

  19. Derekfar表示:

    matadorbet bid: matadorbet bid – matadorbet bid

  20. I am really impressed together with your writing talents as neatly as with the layout to your weblog.
    Is this a paid subject matter or did you modify it your self?
    Either way stay up the excellent quality writing,
    it’s rare to look a great weblog like this one nowadays..

  21. Timothy表示:

    20 Fun Informational Facts About Private Psychiatrist Near
    Me best private psychiatrist london – Timothy,

  22. LarryCoell表示:

    denemebonusuverensiteler.top deneme bonusu veren siteler yerliarama.org deneme bonusu veren siteler yerliarama.org

  23. I read this article completely concerning the resemblance of most recent
    and preceding technologies, it’s awesome article.

  24. HassanbuifS表示:

    http://matadorbet.bid/# matadorbet.bid
    deneme bonusu veren siteler 2024

  25. Every weekend i used to visit this site, because i want enjoyment, since this this web page conations in fact fastidious funny information too.

  26. LarryCoell表示:

    en cok kazand?ran slot oyunlar? en cok kazand?ran slot oyunlar? en kazancl? slot oyunlar?

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

發佈留言

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