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,683,359 Responses

  1. Good day very nice blog!! Guy .. Beautiful .. Wonderful ..

    I will bookmark your web site and take the feeds additionally?
    I am satisfied to find numerous useful information here within the publish, we’d like develop more techniques on this regard, thank you
    for sharing. . . . . .

  2. Williamwhogs表示:

    olympe casino: olympe casino – olympe casino cresus

  3. AlbertShund表示:

    https://olympecasino.pro/# olympe casino avis

  4. VictorVal表示:

    olympe casino: olympe casino en ligne – casino olympe

  5. Diplomi_tnMl表示:

    купить школьный аттестат за 11 классов купить школьный аттестат за 11 классов .

  6. Fascinating web content, I will certainly look into http://www.com Tamil sex video following.

  7. That is a great tip particularly to those fresh to the blogosphere.
    Brief but very precise information… Thanks for sharing this one.

    A must read post!

  8. Felipelaw表示:

    Своевременная помощь позволяет снизить риск осложнений и ускорить процесс детоксикации организма.
    Выяснить больше – снятие наркологической ломки в краснодаре

  9. Gregoryron表示:

    olympe casino: olympe – olympe

  10. Williamwhogs表示:

    casino olympe: olympe – olympe casino en ligne

  11. AlbertShund表示:

    https://olympecasino.pro/# olympe casino en ligne

  12. Ronaldbet表示:

    olympe casino avis olympe casino

  13. Hello! I know this is kinda off topic but I was wondering which blog platform are you using for this site?
    I’m getting sick and tired of WordPress because I’ve
    had problems with hackers and I’m looking at
    options for another platform. I would be fantastic if you could point me in the direction of a good platform.

    My website https://blogs.Koreaportal.com/bbs/board.php?bo_table=free&wr_id=3939075

  14. Williamwhogs表示:

    olympe casino en ligne: olympe casino en ligne – olympe casino en ligne

  15. AlbertShund表示:

    https://olympecasino.pro/# casino olympe

  16. situs togel表示:

    Fantastic beat ! I would like to apprentice at the same time as you amend
    your web site, how can i subscribe for a weblog website? The account aided me
    a appropriate deal. I had been tiny bit familiar of this your broadcast offered brilliant transparent concept

  17. Why Online Casinos Have Become Highly Preferred Worldwide

    Online casinos have transformed the betting scene, delivering a unique kind of accessibility and selection that traditional casinos can’t match. Over time, millions of players globally have chosen the excitement of virtual gambling because of its availability, appealing qualities, and continuously increasing game libraries.

    One of the strongest selling points of digital gambling sites is the vast range of games ready to play. Whether you prefer engaging with retro one-armed bandits, immersing yourself in narrative-rich thematic slots, or mastering skills in table games like Blackjack, casino websites feature countless opportunities. A large number of platforms moreover include live gaming streams, giving you the chance you to communicate with human game hosts and co-players, all while experiencing the immersive atmosphere of a land-based casino without leaving your home.

    If you’re exploring for the first time with the world of virtual gambling or would like to discover reliable sites, why not participate in our active gaming forum? It’s a place where players exchange stories, enabling you to get the most out of your gaming journey. Dive into the community and see it here now: vavada casino.

    Besides the wide selection, internet-based gambling hubs excel constant connectivity.

  18. AlbertShund表示:

    https://olympecasino.pro/# olympe casino en ligne

  19. Thanks for one’s marvelous posting! I actually enjoyed reading it,
    you can be a great author. I will ensure that I bookmark your blog and will
    often come back later on. I want to encourage you to definitely continue your great job, have a nice day! https://wolvesbaneuo.com/wiki/index.php/User:Ezekiel22D

  20. JosephCrimi表示:

    This article will tell you in more detail how to register with 1xBet with a promotional code https://anotepad.com/notes/67ccbrj9

  21. VictorVal表示:

    casino olympe: olympe casino avis – casino olympe

  22. Jariorrtu表示:

    Мы предлагаем выгодно и быстро заказать диплом, который выполнен на оригинальной бумаге и заверен мокрыми печатями, штампами, подписями. Диплом способен пройти лубую проверку, даже с использованием профессионального оборудования. saopaulofansclub.com/read-blog/10491_kupit-diplom-menedzhera-s-zaneseniem-v-reestr.html

  23. I always spent my half an hour to read this website’s articles or reviews everyday
    along with a cup of coffee.

  24. AlbertShund表示:

    https://olympecasino.pro/# olympe casino

發佈留言

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