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,141,426 Responses

  1. Will Upvc Front Doors Supplied And Fitted Near Me One Day Rule The World?
    Upvc Door And Window

  2. Andrewbar表示:

    African elephants use names to call each other, study suggests
    tripscan tor
    Wild African elephants may address each other using individualized calls that resemble the personal names used by humans, a new study suggests.

    While dolphins are known to call one another by mimicking the signature whistle of the dolphin they want to address, and parrots have been found to address each other in a similar way, African elephants in Kenya may go a step further in identifying one another.

    These elephants learn, recognize and use individualized name-like calls to address others of their kind, seemingly without using imitation, according to the study published Monday in the journal Nature Ecology and Evolution.
    The most common type of elephant call is a rumble, of which there are three sub-categories. So-called contact rumbles are used to call another elephant that is far away or out of sight. Greeting rumbles are used when another elephant is within touching distance. Caregiver rumbles are used by an adolescent or adult female toward a calf she is caring for, according to the study.

    The researchers looked at these three types of rumbles, using a machine-learning model to analyze recordings of 469 calls made by wild groups of females and calves in Amboseli National Park and Samburu and Buffalo Springs National Reserves between 1986 and 2022. All the elephants could be individually identified by the shape of their ears, as they had been monitored continuously for decades, according to the study.

    The idea was that “if the calls contained something like a name, then you should be able to figure out who the call was addressed to just from the acoustic features of the call itself,” said lead study author Mickey Pardo, an animal behaviorist and postdoctoral fellow at Cornell University in New York.

    The researchers found that the acoustic structure of calls varied depending on who the target of the call was.

    The machine-learning model correctly identified the recipient of 27.5% of calls analyzed, “which may not sound like that much, but it was significantly more than what the model would have been able to do if we had just fed it random data,” Pardo told CNN.

    “So that suggests that there’s something in the calls that’s allowing the model to identify who the intended receiver of the call was,” he added.

  3. Best slots表示:

    The Most Common New Slots Online Mistake Every Beginner Makes Best slots

  4. This Is The Ugly Reality About Unique Slots Best slots [Bookmarkstore.download]

  5. AndrewHef表示:

    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.

  6. See What Truck Accidents Lawyer Near Me Tricks The
    Celebs Are Using truck Accident

  7. I just couldn’t leave your site prior to suggesting that I extremely enjoyed the usual info a person supply to your guests?

    Is going to be back regularly in order to check up on new
    posts

  8. 비아그라 개요
    비아그라의 과학: 이작은 파란색 알약이 삶을 변화시키는 방법

  9. The Unspoken Secrets Of Online Shopping Websites List Kitchen scale for Baking

  10. среди {самых|наиболее{распространенных|популярных|востребованных|прославленных|знаменитых|именитых}.

    Also visit my web-site; https://pin-up-casino70.xyz/

  11. discuss表示:

    Spot on with this write-up, I seriously believe that
    this site needs a great deal more attention. I’ll probably be returning to see more,
    thanks for the advice!

  12. letts.org表示:

    The Next Big Thing In Modern Slots casino slot tournaments (letts.org)

  13. download mp3表示:

    I read this post completely regarding the resemblance of latest and earlier technologies, it’s awesome article.

  14. You made some good points there. I checked on the internet to
    find out more about the issue and found most individuals will go along with
    your views on this site.

  15. Magnificent beat ! I wish to apprentice while you amend your web site, how
    could i subscribe for a blog web site? The account helped me a acceptable
    deal. I had been tiny bit acquainted of this your broadcast offered bright clear idea

  16. stus bokep表示:

    Hello, i read your blog from time to time and i own a similar one and i was just
    wondering if you get a lot of spam remarks? If so how do you prevent it, any plugin or anything you can suggest?
    I get so much lately it’s driving me crazy so any help is very much appreciated.

  17. 10 Instagram Accounts On Pinterest To Follow Mini Cooper Replacement Key
    mini key not working – http://www.freelegal.ch,

  18. The Best Advice You Could Ever Receive On Accident Legal accident law firm

  19. hey there and thank you for your info – I have certainly picked up something new from right
    here. I did however expertise a few technical
    points using this website, as I experienced to reload the
    site a lot of times previous to I could get it to load
    properly. I had been wondering if your web hosting is OK?
    Not that I’m complaining, but sluggish loading instances times will often affect your placement in google and
    could damage your high-quality score if advertising and marketing
    with Adwords. Anyway I’m adding this RSS to my e-mail and can look out for much more of your respective intriguing content.
    Make sure you update this again very soon.

  20. This Is The Ugly Truth About Personal Injury Compensation Personal Injury law firms

  21. THC vapes UK表示:

    Thank you for the good writeup. It in fact was a amusement account it.
    Look advanced to far added agreeable from you! However, how can we communicate?

  22. StanleyJoype表示:

    Драгон Мани Казино https://krpb.ru – ваше место для азартных приключений! Наслаждайтесь широким выбором игр, щедрыми бонусами и захватывающими турнирами. Безопасность и честная игра гарантированы. Присоединяйтесь к нам и испытайте удачу в самом захватывающем онлайн-казино!

  23. Regards. Numerous info!

  24. You’ll Be Unable To Guess Truck Accident Claims’s Benefits truck accident lawsuits

  25. Three Greatest Moments In Shopping Online Uk History Direct-Fit Intercooler St

  26. 15 Startling Facts About Slot Apps That You Never Knew scatter slots
    [https://www.deepzone.Net/]

  27. 9 Lessons Your Parents Taught You About Double Glazed Window Suppliers Near Me double Glazed window suppliers near me

發佈留言

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