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

  1. News表示:

    Hi there would you mind stating which blog platform you’re working with?

    I’m going to start my own blog soon but I’m having a difficult time deciding between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your layout seems different then most blogs and I’m looking for something completely unique.
    P.S Sorry for being off-topic but I had to ask!

  2. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт телефонов infinix, можете посмотреть на сайте: ремонт телефонов infinix рядом
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  3. The Most Worst Nightmare About Link Collection Relived 링크모음
    (k12.Instructure.com)

  4. DanielAbice表示:

    http://prednibest.com/# 25 mg prednisone

  5. Unquestionably consider that that you said. Your favorite reason appeared to be at
    the web the easiest thing to bear in mind of. I say to
    you, I definitely get irked at the same time as other people
    think about concerns that they just don’t realize
    about. You controlled to hit the nail upon the
    highest and defined out the whole thing without having side-effects ,
    folks can take a signal. Will probably be back to get more.
    Thanks

  6. This paragraph will assist the internet people for creating new
    blog or even a weblog from start to end.

  7. Nikefut表示:

    tor dark web darknet drugs dark markets

  8. проект перепланировки квартиры для согласования цена [url=http://zakazat-proekt-pereplanirovki-kvartiry11.ru/]проект перепланировки квартиры для согласования цена[/url] .

  9. "Free Gift"表示:

    Greatt ƅlolg yⲟuu havve һefe buut І wɑas wonrering iff yoou knbew off anyy messxage bօrds tthat
    cover tthe sasme toplics discusаed herе? I’d reaⅼpy lіke
    tto bbe a part oof ɡrouyp where I ccan geet opinuons frolm otyer knowledgeable individᥙaalѕ thaat shуare thee same interеst.
    If yoou hhave anny reⅽommendations, plpease lett mme ҝnow.
    Blezs үou!

    My site “Free Gift”

  10. This page truly has all the info I wanted about this
    subject and didn’t know who to ask.

  11. мебельный поролон купить москва [url=http://porolon-dlya-divana.ru]мебельный поролон купить москва[/url] .

  12. Everything is very open with a very clear description of the challenges.
    It was truly informative. Your website is extremely helpful.

    Thanks for sharing!

  13. Здесь можно купить сейф домашний сейф домашний купить

  14. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт телефонов infinix, можете посмотреть на сайте: ремонт телефонов infinix в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  15. пенополиуретан для дивана купить пенополиуретан для дивана купить .

  16. Ashly表示:

    20 Trailblazers Are Leading The Way In Realistic Silicone Sex Doll realistic
    silicone sex dolls (Ashly)

  17. I love your blog.. very nice colors & theme.
    Did you create this website yourself or did you hire someone to do
    it for you? Plz answer back as I’m looking to create my own blog and would like to know where u got
    this from. thanks

  18. iconwin login表示:

    Your mеans oof explaining ɑll in this article іs really pleasant, evwry one caan simply understand it, Thnks a lot.

    my pɑge … iconwin login

  19. электрокарниз для зашторивания окон купить https://elektrokarniz-dlya-shtor499.ru .

  20. Nikefut表示:

    darkweb marketplace darknet seiten darkmarket link

  21. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт телефонов honor адреса, можете посмотреть на сайте: срочный ремонт телефонов honor
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  22. Belle Gregory表示:

    Remodeling houses often begins outside first, especially focusing heavily upon boundaries established via walls/fences/etc Cheap fencing contractors

  23. Hello to every body, it’s my first pay a visit of this webpage; this webpage includes awesome and genuinely fine
    information in favor of visitors.

發佈留言

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