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,525,112 Responses

  1. Wow, this wall art is absolutely jaw-dropping! Kanye’s Graduation era
    was such a masterpiece in the creative space, and this cover truly revolutionizes the dreamy
    essence of that time.

    The dynamic color scheme and the flying bear jetting through the starry horizon make it feel so
    limitless.

    This is definitely a dream collectible for any visionary thinker!

  2. гинеколог порно [url=www.ginekolog-rukoeb1.ru/]гинеколог порно[/url] .

  3. осмотр гинеколога порно http://www.ginekolog-rukoeb1.ru .

  4. Dannyfut表示:

    darkmarket url https://github.com/darknetmarketslinks/darknetmarketlinks – darknet seiten darkmarket url

  5. Porterfax表示:

    easy canadian pharm canadian online pharmacy easy canadian pharm

  6. Porterfax表示:

    easy canadian pharm pharmacy in canada easy canadian pharm

  7. MarkWat表示:

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

  8. How The 10 Most Disastrous You Can Buy A Driving License Fails
    Of All Time Could Have Been Prevented motorradführerschein kaufen

  9. WillieRap表示:

    buying prescription drugs in mexico online: xxl mexican pharm – purple pharmacy mexico price list

  10. The 9 Things Your Parents Taught You About Psychiatrist Private psychiatrist Private

  11. Davidmoits表示:

    drugmart: discount drug mart pharmacy – drugmart

  12. Rodneytus表示:

    dark web market links https://github.com/darkwebmarketslinks/darkwebmarkets – dark market onion blackweb official website

  13. MichaelGeony表示:

    canadian prescription pharmacy http://megaindiapharm.com/# indian pharmacy

  14. Dannyfut表示:

    darknet search engine https://github.com/darknetmarketslinks/darknetmarketlinks – dark website darknet links

  15. The digital era has reshaped how people experience gambling, making online casinos more popular than ever, allowing players to enjoy high-quality gaming without leaving their homes. No longer do players need to visit physical casinos, because online platforms offer everything from classic slots to live dealer games.

    Why Online Casinos Are So Popular

    More and more players are choosing online gambling for its unmatched convenience and variety. Perhaps the most appealing aspect is how easy it is to access games. Unlike physical casinos that have operating hours, online platforms operate 24/7, letting players enjoy their favorite games at any time.

    One of the strongest attractions is the enormous range of gaming options available. Traditional casinos are often limited by space, but online platforms can host thousands of different games. Players can enjoy everything from nostalgic one-armed bandits to modern 3D slots packed with special features.

    Stay updated with the latest casino news, exclusive bonuses, and expert tips—follow us aviator login

    Unlocking Casino Bonuses
    One of the biggest draws of online casinos is the generous promotions and bonuses. New players are often welcomed with attractive sign-up bonuses, deposit matches, and free spins. Loyal customers are rewarded with tiered programs, reloading bonuses, and special incentives.

    Luck vs. Skill in Online Gambling
    While many casino games are based purely on luck, some require skill and strategy. Poker, for instance, is a game of skill where experienced players can outplay beginners by reading opponents and making calculated decisions. On the other hand, slot machines and roulette rely entirely on chance, making them ideal for casual players looking for fun and excitement.

    How to Gamble Responsibly Online
    As exciting as online gambling can be, it’s essential to practice responsible gaming. By setting strict financial limits and staying disciplined, players can prevent gambling from becoming a problem. Licensed casinos provide responsible gambling measures, such as cooling-off periods and withdrawal restrictions, to help players stay in control.

    Share Your Casino Experience
    Have you played at an online casino before? What was your experience like? Share your thoughts and experiences in the comments below!

  16. Porterfax表示:

    family pharmacy Cheapest online pharmacy online pharmacy delivery usa

  17. Charleskepsy表示:

    canadian online pharmacy no prescription https://familypharmacy.company/# Online pharmacy USA

  18. Link exchange is nothing else but it is simply placing the other person’s weblog link on your page at appropriate place and other person will
    also do similar for you.

  19. Superb blog you have here but I was curious about if you knew
    of any forums that cover the same topics discussed here?
    I’d really love to be a part of online community where I can get responses from other knowledgeable people that share the same interest.

    If you have any suggestions, please let me know.

    Many thanks!

發佈留言

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