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...

976,675 Responses

  1. demo slots表示:

    The Novice Slots Success Story You’ll Never Remember
    demo slots

  2. Легко ли быть наблюдателем, когда вокруг творится зло и нельзя вмешаться, навести порядок, защитить? Главный герой этого романа – дон Румата (землянин Антон), который попадает на планету Арканар с экспериментальным миром. На этой планете царит средневековая жестокость, фальшь и борьба за власть. Но Румата не должен вмешиваться. Он ученый, который проводит эксперимент. Однако человек в нем берет вверх над ученым, сердце побеждает рассудок. Разве можно спокойно наблюдать, как зло побеждает добро, как талант растаптывается, а справедливости не существует? Главному герою это не удается…
    https://knigavuhe.org/book/84-strugackie-arkadijj-i-boris-trudno-byt-bogom/

  3. Modern Slots表示:

    15 Things Your Boss Would Like You To Know You’d Known About
    Best Slots Modern Slots

  4. BryanDwelt表示:

    The original occupant of an Egyptian sarcophagus was unknown. Then a tiny ornament revealed a very big name
    tripscan ссылка

    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.

  5. 14 Smart Ways To Spend Your On Leftover Replacement Keys Car Budget car key battery replacement near me (http://www.Rent-cha.com)

  6. slot gacor表示:

    I was curious if you ever considered changing
    the structure of your blog? Its very well written; I love
    what youve got to say. But maybe you could a little more
    in the way of content so people could connect with it better.
    Youve got an awful lot of text for only having 1 or two images.
    Maybe you could space it out better?

  7. Professional SEO Company London Explained In Fewer Than 140
    Characters content Creation companies

  8. 16 Must-Follow Instagram Pages For Hiring Truck
    Accident Attorneys-Related Businesses Truck accidents

  9. Lawsuits表示:

    15 Top Pinterest Boards Of All Time About Workers Compensation Claim Lawsuits

  10. Stewart表示:

    What’s The Job Market For Double Glazed Repairs Near Me
    Professionals Like? double glazed repairs near
    me, Stewart,

  11. 10 Amazing Graphics About Uk Online Shoe Shopping Websites Eco-Friendly Dog Treats

  12. fela law firm表示:

    What’s The Reason? Fela Lawyers Is Everywhere This Year fela law firm

  13. This Week’s Most Popular Stories About Which
    Is The Best Online Supermarket Which Is The Best Online Supermarket small linen rug

  14. The 10 Most Terrifying Things About Free Spin Slots free spin Slots (https://shorl.Com)

  15. You’ll Be Unable To Guess Treadmills Folding Treadmills’s Tricks Treadmills Folding treadmills

  16. Shana表示:

    25 Surprising Facts About Slot Bonuses play slots – Shana,

  17. What’s The Current Job Market For Double Glazing Repairs
    Near Me Professionals? double glazing repairs near me

  18. A Look At The Future: What Will The Slot Variance Industry Look Like In 10 Years?
    high variance slots (https://community.umidigi.com/home.php?mod=space&uid=1164261)

  19. What The 10 Most Worst Erb’s Palsy Claim Errors Of All Time Could Have Been Prevented Erb’s Palsy Lawyers

  20. in that case, if you plant a trust wallet, https://https://green-bitcoin.app// wallet, you can pass to 1inch for doing a transaction.

  21. You’ll Never Guess This Upvc Door Panel Replacement’s Benefits
    Upvc Door Panel

  22. Shela表示:

    Your Family Will Thank You For Having This Lexus Key lexus keyless
    entry (Shela)

  23. bokep indo表示:

    For most recent information you have to visit web and
    on web I found this site as a best web site for latest updates.

  24. Roseanna表示:

    Cheapest Online Grocery Shopping Uk Isn’t As Tough As You
    Think cheap online grocery shopping uk (Roseanna)

  25. Expert Advice On CS GO Open Case Website From A Five-Year-Old case operation bravo

  26. Amazing plenty of good advice!

  27. Medication information sheet. Cautions.
    cost fosamax without dr prescription
    Best news about pills. Read information here.

  28. 5 Laws To Help The Personal Injury Claim Industry Personal Injury lawsuits

發佈留言

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