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,142,135 Responses

  1. We are a group of volunteers and opening a new scheme in our community.

    Your website offered us with valuable information to work on. You have
    done an impressive job and our entire community will be grateful to
    you.

  2. Everything You Need To Learn About Winning Slots evoplay Slots Payouts

  3. jennifeBoT表示:

    ОГО , ну наконецто
    вентилируемые фасады работа, навесный вентилируемые фасады привлекает интерес профессионалов и заказчиков. Такие конструкции обеспечивают значительный показатель теплоизоляции, минимизируя затраты на отопление. Также, вентилируемые фасады работа обеспечивают эффективную вентиляцию, что не допускает образованию конденсата и плесени. Эта технология является экологически безвредной. Вентилируемые фасады работа также повышают эстетику зданий.

  4. Whoa many of terrific information!

  5. We’re a group of volunteers and starting a new scheme in our community.
    Your website provided us with useful info to work on. You’ve performed a formidable process and our whole community will
    likely be thankful to you.

  6. Medicines information leaflet. Effects of Drug Abuse.
    how to get cheap oxcarbazepine no prescription
    All trends of medicine. Get information now.

  7. 5 Laws Everybody In Slot Trends Should Be Aware Of Top Mobile Slots – Bbs.Qupu123.Com,

  8. Where Do You Think New Upvc Door Be 1 Year From Now? upvc Door Repair near me

  9. posnara.com表示:

    The One SEO Software Trick Every Person Should Know ranking seo tool, posnara.com,

  10. 20 Questions You Must Always ASK ABOUT Double Glazing In Leeds Before You
    Decide To Purchase It repairs to double glazed windows

  11. MatthewJence表示:

    The original occupant of an Egyptian sarcophagus was unknown. Then a tiny ornament revealed a very big name
    трипскан зеркало

    A sarcophagus discovered in 2009 in an Egyptian burial chamber came with a complicated history: Ancient writing on the stone container showed that it had been used twice, but while its second occupant, the 21st dynasty high priest Menkheperre, was known, the first owner had remained a mystery — until now.

    New clues have surfaced as a result of Frederic Payraudeau, an associate professor in Egyptology at Sorbonne University in Paris, reexamining a fragment of the granite sarcophagus and deciphering the hieroglyphs engraved on it. Tucked away in the cartouche, an oval-shaped ornament often found in tombs, he found a name of a very recognizable figure: Ramesses II.
    Payraudeau said the inscription is evidence that the artifact was originally from the tomb of the famous pharaoh and had been reused after looting.

    “Clearly, this was the sarcophagus of a king,” Payraudeau said. “The cartouche dates back to its first usage, and contains Ramesses II’s throne name, Usermaatra. He was the only pharaoh to use this name during his time, so that cleared any doubt that it was his sarcophagus.”

    The findings, published in the journal Revue d’Egyptologie, add to the lore of Ramesses II, also known as Ozymandias and one of Egypt’s most celebrated pharaohs. It also fills a gap in our understanding of how sarcophagi were used to entomb kings.
    Ramesses II was the third king of the 19th dynasty, and his reign — from 1279 to 1213 BC — was the second longest in the history of Egypt. He was known for his victorious military campaigns and an interest in architecture, which led him to order up important monuments and statues of himself. His mummy is at the National Museum of Egyptian Civilization in Cairo.

    Another coffin belonging to Ramesses II was discovered in 1881 near Luxor, but the sarcophagus fragment analyzed in the study was found in Abydos, a city about 40 miles (64 kilometers) to the northwest in a straight line.

    “That is less bizarre than it seems,” Payraudeau said, “because we know his tomb was looted in the antiquity, maybe two centuries after his death, and he’s certainly not the only king to have been looted.”

    The granite fragment, which is a nearly complete part of the longer side of the sarcophagus, was previously believed to have belonged to a prince. “But I always found this strange, because the decoration on this carefully crafted piece was indicative of a king, and had elements traditionally reserved for kings,” Payraudeau said.

  12. CharlesFrien表示:

    Guidebook on Imitation Luxury Purses

    Motives of a Fame for Replica Upscale Accessories

    Replica Luxury Handbags Possess Surged In Fame BecauseOf Numerous Persuasive Reasons

    Cost Represent Regularly An Driving Motivation

    Outstanding Versions Present A Allure About Designer Designers No An Hefty Cost
    Breakthroughs In Building Represent Which These Copies Commonly Possess Remarkable Resemblances About The Genuine

    For Those That Appreciate Fashion Yet Be Budget-Conscious

    Version High-End Bags Offer A Inviting Option

    Recommendations With Recognizing Reality

    Analyzing Details Like Logos Seams Together Accessories

    Might Assist FigureOut An Copy’s Authenticity

    Matching These Characteristics To Visuals From Genuine Brand Baggage

    Will Disclose Multiple
    Alternative InsteadOf Imitation High-End Luggage

    Reasonable Designer Replacements

    Represent Obtainable That Offer Stylish Choices Without TradingOff With High Standards

    These Products Are Formally Constructed From Brands Who Give High-End Style At Attainable

  13. 11 Methods To Totally Defeat Your Online Shopping S97017648 Oem Part

  14. 11 Ways To Destroy Your Affordable SEO Service Uk affordable Seo strategies near me

  15. 3D Slots表示:

    10 Inspirational Graphics About Slot Experiences 3D Slots

  16. Guide To Slot Demo Gates Of Gatot Kaca: The Intermediate Guide In Slot
    Demo Gates Of Gatot Kaca slot demo gates Of gatot kaca

  17. bokep表示:

    What’s up, constantly i used to check web site posts here early in the morning, because i like to learn more
    and more.

  18. Nicely put, Thank you.

  19. Medical Malpractice Lawyers Tools To Improve
    Your Everyday Lifethe Only Medical Malpractice Lawyers Trick That Everyone Should Be Able
    To medical malpractice lawyer

  20. It’s in fact very complex in this active life to listen news on Television, thus I only use the
    web for that purpose, and take the hottest news.

  21. Lhaneevige表示:

    Делаем отличное предложение вам выполнить консультацию (аудит) по подъему продаж и прибыли в вашем бизнесе. Формат аудита: персональная встреча или конференция по скайпу. Делая очевидные, но простые действия, доход от ВАШЕГО коммерциала можно превознести в несколькио раз. В нашем багаже более 100 испытанных практических методологий увеличения продаж и прибыли. В зависимости от вашего бизнеса выберем для вас наиболее сильные и будем постепенно претворять в жизнь.
    https://vniikukuruzy.ru/

  22. Katherin表示:

    7 Secrets About Replacement Window Handle That Nobody Can Tell You upvc replacement
    window handles (Katherin)

  23. Shantae表示:

    14 Clever Ways To Spend Extra Money Slot Mechanics Budget top-rated online slots – Shantae

  24. link bokep表示:

    certainly like your website however you have to check the spelling on quite a few of your posts.
    Several of them are rife with spelling issues and I find it very troublesome to
    tell the truth on the other hand I’ll definitely come again again.

  25. bokep jepang表示:

    Wow, this post is fastidious, my younger sister is
    analyzing such things, thus I am going to tell her.

  26. 10 Healthy Online Shopping Website In London Habits Waterproof Pet Bed

  27. Good day! Would you mind if I share your blog with my facebook group?
    There’s a lot of people that I think would really enjoy your content.

    Please let me know. Thank you

  28. Meds prescribing information. Effects of Drug Abuse.
    buying rogaine without insurance
    Some news about pills. Read now.

  29. Fun Slots表示:

    10 Beautiful Graphics About Play Slots Fun Slots

  30. Luther表示:

    The Next Big Trend In The Trusted Online Shopping Sites For Clothes Industry
    Rugged Laptop Case (Luther)

發佈留言

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