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,842 Responses

  1. Porterfax表示:

    canadian pharmacy without prescription drugmart discount drug pharmacy

  2. MichaelGeony表示:

    best online pharmacy no prescription https://easycanadianpharm.shop/# easy canadian pharm

  3. Davidmoits表示:

    canadian pharmacy checker: easy canadian pharm – easy canadian pharm

  4. The Most Powerful Sources Of Inspiration Of Sash Window Repair Replacing sash Cords

  5. MarkWat表示:

    Всем привет! Может кто знает, где найтиразные блоги о кредитах? Пока нашел – https://jet-ready.ru

  6. 1win_kxOa表示:

    официальный сайт 1win https://fabc.com.kg .

  7. Rodneytus表示:

    darkmarket 2025 https://github.com/darkwebmarketslinks/darkwebmarkets – dark web drug marketplace dark web site

  8. 1 vin_snSi表示:

    вывод средств 1win https://bbcc.com.kg .

  9. This post will help the internet people for
    setting up new web site or even a blog from start to end.

  10. Charleskepsy表示:

    pharmacy without prescription https://easycanadianpharm.com/# canadian online drugstore

  11. MichaelGeony表示:

    prescription drugs from canada https://xxlmexicanpharm.com/# п»їbest mexican online pharmacies

  12. Rodneytus表示:

    dark markets 2025 https://github.com/darkwebmarketslinks/darkwebmarkets – darknet sites black internet

  13. Davidmoits表示:

    Cheapest online pharmacy: online pharmacy delivery usa – Cheapest online pharmacy

  14. MichaelGeony表示:

    mail order pharmacy no prescription http://discountdrugmart.pro/# discount drug mart

  15. Charleskepsy表示:

    pharmacy coupons https://xxlmexicanpharm.com/# mexican border pharmacies shipping to usa

  16. The rise of online casinos has revolutionized the gambling industry, making it more accessible, convenient, and thrilling than ever before. Now, gamblers don’t have to travel to experience the thrill of betting, as the full casino experience is accessible from desktops, tablets, and smartphones.

    Reasons Why Online Casinos Are Booming

    The surge in popularity of online casinos is driven by several factors. One of the biggest advantages is accessibility. While land-based casinos have restrictions, online platforms operate 24/7, letting players enjoy their favorite games at any time.

    Another major reason for their popularity is the sheer variety of games. 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 bet

    Bonuses, Rewards, and Promotions
    Bonuses and special offers make online gambling even more enticing. 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.

    Choosing Between Luck-Based and Skill-Based Games
    Depending on your preferences, you can choose between pure chance games or those where skill makes a difference. 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.

    Finding a Secure and Fair Casino
    While online casinos offer fun and potential winnings, responsible gambling is crucial. By setting strict financial limits and staying disciplined, players can prevent gambling from becoming a problem. Trustworthy sites encourage responsible play through features like voluntary betting caps and time-out options.

    Let’s Talk About Online Casinos
    Have you played at an online casino before? What was your experience like? Share your thoughts and experiences in the comments below!

  17. How Online Casinos Remain a Global Phenomenon

    Digital casinos have reshaped the gambling industry, offering a level of accessibility and range that traditional establishments fall short of. In recent years, a vast number of enthusiasts across the globe have embraced the thrill of digital casino play because of its always-open nature, exciting features, and widening catalogs of games.

    One of the strongest selling points of internet-based platforms is the vast selection of choices ready to play. Whether you enjoy engaging with classic reel games, exploring plot-filled visual slot games, or mastering skills in table games like Blackjack, digital casinos deliver infinite possibilities. Numerous services moreover feature live dealer games, letting you to participate with human game hosts and co-players, all while experiencing the authentic environment of a real casino in your own space.

    If you’re a beginner with the world of online gaming or would like to discover reputable operators, why not join our vibrant community? It’s a platform where fans share tips, helping you to improve your virtual play. Check out the experience and visit us now: ????? ?????? 1xbet ?????????

    Besides the wide selection, online casinos are known for accessibility.

  18. mikamart.Ru表示:

    Unexpected Business Strategies That Aided Buy Category C Driving License Succeed
    Comprar a carta de conduçãO do IMT, mikamart.Ru,

  19. Charleskepsy表示:

    pharmacy online 365 discount code https://discountdrugmart.pro/# canadian pharmacy without prescription

  20. apk slot 777表示:

    Apkslot adalah situs games apk slot online paling banyak di download oleh masyarakat
    karena memiliki pelayanan profesional serta bonus besar untuk seluruh member, tersedia banyak pilihan permainan dengan grafik bagus memuaskan

  21. It’s an amazing post in support of all the web viewers; they will take benefit from it I am sure.

  22. MichaelGeony表示:

    mail order prescription drugs from canada https://discountdrugmart.pro/# drug mart

發佈留言

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