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,233,066 Responses

  1. Trefsqn表示:

    Можно ли купить аттестат о среднем образовании, основные моменты и вопросы
    povzroslomu.kabb.ru/viewtopic.php?f=3&t=115

  2. 10 Inspirational Graphics About Asbestos Mesothelioma Mesothelioma Lawyer

  3. Car Key Programmed: The History Of Car Key Programmed In 10 Milestones car key reprogram Near me

  4. Devin表示:

    The 10 Most Terrifying Things About Private Adhd Assessment London adhd assessment london (Devin)

  5. HassanbuifS表示:

    http://casinositeleri.win/# guvenilir casino siteleri
    deneme bonusu veren siteler yerliarama.org

  6. Wonderful website you have here but I was wondering
    if you knew of any user discussion forums that cover the same topics discussed in this article?
    I’d really like to be a part of group where I can get feed-back from other experienced people that share
    the same interest. If you have any recommendations, please let me know.
    Thank you!

  7. HassanbuifS表示:

    https://matadorbet.bid/# matadorbet
    deneme bonusu veren siteler yeni

  8. sandibet表示:

    Wow, this article is good, my younger sister is analyzing such things, therefore I am going to convey her.

  9. Water Damage表示:

    Howdy would you mind stating which blog platform you’re working with?
    I’m looking to start my own blog soon but I’m having a tough time making a decision between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your layout seems different then most blogs and I’m looking for something
    completely unique. P.S Apologies for being off-topic but I had to ask!

  10. HassanbuifS表示:

    http://ultrabet-tr.online/# ultrabet yeni giris 1125
    deneme bonusu veren siteler yerliarama.org

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

  12. 匿名訪客表示:

    Ich habe michvor kurzembei Spinsy Casinoangemeldetund warbeeindrucktvomgroßzügigenWillkommensbonus!

    Er hat meinemBudgeteinen echten Schub gegeben und mir die Möglichkeit geboten,unterschiedliche Gamesohne Druckzu testen. DieeinfacheNavigationerleichtert das Findender Spielesehr leicht.
    EinefantastischeWahl fürSpieler jeder Art!

  13. Medicament information. Short-Term Effects.
    mirtazapine and male libido
    Actual about medicament. Read information now.

  14. Derekfar表示:

    casino siteleri win: Deneme Bonusu Veren Siteler – guvenilir casino siteleri

  15. The 10 Scariest Things About Car Key Cut Key Cutting services, world-news.wiki,

  16. 2 In 1 Pram System Tools To Help You Manage Your Daily Life 2 In 1 Pram
    System Trick Every Person Should Know 2 In 1 Pram System

  17. What’s up, after reading this amazing piece of writing i am as well
    glad to share my know-how here with colleagues.

    https://w6.livecambodia.life/

  18. A Glimpse In Mobile Car Diagnostics’s Secrets Of Mobile
    Car Diagnostics diagnostic scanner – https://Traycereal94.werite.net

  19. Double Glazing Repairs Near Me Tools To Streamline Your Daily Life Double Glazing Repairs Near Me Trick That Everyone Should Know double glazing repairs near me

  20. bk8 goal表示:

    Remarkable Entry Feedback
    Wow , what a compelling blog ! I truly
    savored digesting your viewpoints on this subject .

    As someone who has been tracking your website
    for a duration , I need to say that this is alongside your finest well-written and mesmerizing content
    so far .
    The style you interlaced multiple perspectives and scientific data was truly astounding .
    I found myself nodding as I perused , as your points simply
    came across to advance remarkably effortlessly .

    My web blog bk8 goal

  21. JohnnyTex表示:

    Веб агентство в Москве выполняет разработку сайтов на платформе Битрикс под ключ. Дополнительные услуги – продвижение в поисковых системах Яндекс и Гугл, техническая поддержка, обслуживание, аудит, тестирование, наполнение контентом, контекстная реклама и маркетинг сайты на битрикс

  22. 8 Tips To Up Your Fire Suite Electric Game extra large electric fireplace with mantel
    (https://git.openprivacy.ca/)

發佈留言

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