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,518,425 Responses

  1. ZenBusiness uses the finest registration alternatives.

    my web page :: services on amazon

  2. The best cbd oil for cats items are made from premium hemp
    CBD.

  3. XYGENYX, a licensing business for FDA-registered items.

    My blog post: ai detector turnitin free reddit

  4. They have products to sell or services to offer.

    Feel free to visit my page :: ai detector turnitin free

  5. I don’t even know how I finished up right here, but I thought this publish was once great.

    I do not realize who you’re but certainly you’re going to
    a well-known blogger for those who are not already ;
    ) Cheers!

    Take a look at my webpage; sexual assault victim lawyers near me

  6. In this case, the life insurance company’s cash.

    My homepage heavy duty truck Parts amarillo tx

  7. AshleApox表示:

    https://mostbet-vdr3.top/ о крупнейшем онлайн-казино Mostbet и как получить промокод для бонусов и акций.

  8. Authentic HGH Rewards (NewULife Hgh Gel Not Checked Yet).

    Here is my blog post ai detector for essays turnitin

  9. infrared sauna blanket saunas vary in price from $130 to $3,000.

  10. USP human development hormone (somatropin).

    Here is my blog: ai detector for college essays

  11. USP human growth hormone (somatropin).

    Have a look at my web page :: google ads agency

  12. Perryzoozy表示:

    Pharmacie sans ordonnance kamagra oral jelly pharmacies en ligne certifiГ©es

  13. Jacobbep表示:

    acheter mГ©dicament en ligne sans ordonnance https://kamagrameilleurprix.com/# Pharmacie en ligne livraison Europe

  14. GeorgeHal表示:

    кликните сюда rox casino

  15. The best cbd oil for cats items are made from top notch hemp CBD.

  16. On both plans, there are no ongoing payments required.

    my site :: lifetime Mortgage martin lewis

  17. Everyone loves it when individuals come together and share opinions.
    Great blog, keep it up!

    Feel free to surf to my web page – best sexual harassment lawyers nyc

  18. In this situation, the life insurance policy firm’s loan.

    Feel free to visit my site ai detector for essays turnitin

  19. Allow me show you in my review of NewULife.

    Also visit my blog post: ai detector turnitin reddit

  20. WilsonVah表示:

    pharmacie en ligne pas cher: pharmacie en ligne pas cher – pharmacies en ligne certifiГ©es

  21. USP human growth hormone (somatropin).

    Visit my website – ai detector free for teachers

  22. What is New U Life SOMADERM Transdermal Gel.

    Also visit my blog: Ai Detector Free

  23. Kingksf表示:

    Телеграм психолог. Онлайн чат с психологом без регистрации. Онлайн-консультация психолога.

  24. They have items to market or services to offer.

    Also visit my website: heavy duty truck Parts florida

  25. Link - Elani表示:

    Dragon Tiger is believed to have begun in the Cambodian kingdom and has since extended to gaming venues worldwide, particularly in the Asian market. The game’s ease and fast-paced nature have made it a popular choice among both seasoned wagerers and newcomers. Unlike many other card games that require in-depth strategies and skills, Dragon Tiger relies strongly on luck, making it an attractive choice for those looking for a fast gaming experience. At its foundation, Dragon Tiger is like traditional baccarat but modifies the betting system. The game is played with a standard pack of 52 cards, and the goal is to anticipate which of the two hands—Dragon or Tiger—will have a more significant value. Players put their bets before the dealer displays the cards. The hand with the superior card is the winner, and ties are also permissible, adding an extra layer of interest.

    Direct link: https://www.biographyweb.org/bliss-and-zack-the-couple-from-love-is-blind-are-expecting-their-first-child/

    Players can put several types of stakes, including betting on the Dragon, the Tiger, or a tie. The financial gain varies depending on the type of bet placed, with ties typically delivering the most significant payout due to their rarity. This clear-cut betting structure makes Dragon Tiger accessible to a wide audience, further contributing to its popularity in online casinos.

  26. I do not even know how I ended up here, but I thought this post was good.

    I don’t know who you are butt certainly you’re going to
    a famous blogger if you aren’t already 😉 Cheers!

    Also visit myy blog; barem cars yorumlar

發佈留言

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