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,180,114 Responses

  1. iwinfund表示:

    Its such as you learn my thoughts! You seem to grasp a lot approximately this, like you wrote the e-book in it or something.
    I think that you simply could do with a few % to drive the message
    home a bit, however instead of that, that is wonderful blog.
    A fantastic read. I’ll definitely be back.

  2. You’ll Never Guess This Window Replacement
    Near Me’s Secrets Window Replacement Near Me

  3. What’s up to every body, it’s my first go to see of this weblog; this webpage carries awesome and in fact good data for readers.

  4. ChuckUnmab表示:

    Erling Breut Haaland https://erling-haaland.prostoprosport-cz.org je norsky fotbalista, ktery hraje jako utocnik za Anglicky klub Manchester City a norska reprezentace. Rekordman anglicke Premier League v poctu golu za sezonu.

  5. Paylaş düğmesine dokunun ve açılır menüde
    Bağlantıyı Kopyala öğesini bulun.

  6. Ug 234表示:

    I loved as much as you’ll receive carried out right here.
    The sketch is tasteful, your authored subject matter stylish.
    nonetheless, you command get got an shakiness over that you wish be delivering the following.
    unwell unquestionably come more formerly again since exactly the same
    nearly a lot often inside case you shield this increase.

  7. Guide To Buy 1kg Coffee Beans: The Intermediate Guide For Buy 1kg Coffee Beans Buy 1Kg Coffee Beans

  8. Выберите стильные тактичные штаны для повседневной носки, сделанные из качественных материалов.
    Выберите стильные тактичные штаны для своего гардероба, для активного образа жизни.
    Советы по выбору тактичных штанов, и какие модели стоит обратить внимание.
    Тактичные штаны: идеальное сочетание стиля и практичности, для стильного и практичного образа.
    Тактичные штаны: выбор современного мужчины, чтобы чувствовать себя комфортно в любой ситуации.
    куплю тактичні штани https://vijskovitaktichnishtanu.kiev.ua/ .

  9. pg slot表示:

    PG Gaming – best slot online in the Philippines
    better than jili slot and pp slot
    free Spins 3000+ Free Demo Slot

    searching pggaming.org on Google or Bing to get free coins for play

    https://pggaming.org/

  10. 10 Quick Tips About Double Glazed Window Suppliers Near Me Double Glazed Windows Near Me

  11. Ug 234表示:

    I got this site from my pal who informed me on the topic of this site and at the moment this time
    I am browsing this site and reading very informative posts at
    this time.

  12. Thanks in favor of sharing such a pleasant opinion, post is fastidious, thats why i have read it
    completely

  13. Thank you, I have recently been searching for info about this topic for ages and yours is the greatest
    I have found out so far. However, what concerning the bottom line?
    Are you sure about the supply?

  14. What’s Everyone Talking About Auto Accident Lawyers Today
    auto Accidents

  15. In the past century asbestos was used to make a myriad of products stronger, more resistant to fire, and less expensive.
    But exposure to airborne asbestos Settlement fibers can cause lung diseases such as asbestosis and mesothelioma.

  16. 슬롯表示:

    프라그마틱 무료 게임
    Fang Jifan은 잠시 당황한 후 “폐하께서는 정말 예리하십니다 …”라고 말했습니다.

  17. 슬롯表示:

    온라인 슬롯
    느리고 일관성 있게 말하는 것이 분명한데, 생명을 위협하는 매력과도 같다.

  18. 슬롯表示:

    피망 슬롯
    이번에 Akyol을 죽이는 본질은 Suleiman 황제가 옛 귀족들과 결별하도록 격려하는 것이 었습니다.

  19. 슬롯表示:

    신규 슬롯 사이트
    Chen Tong이 여전히 가사부의 하인이라면 이것은 그를 모욕하는 것 같습니다.

  20. Asbestos victims seek mesothelioma Compensation
    from companies responsible for asbestos exposure. This is accomplished
    through personal injury claims and wrongful death
    claims. A competent attorney can help victims and families through the process.

  21. I’m now not certain the place you are getting your information, but good topic.
    I needs to spend a while studying more or understanding
    more. Thank you for wonderful information I used to be on the lookout for this information for my mission.

  22. 4 Dirty Little Tips On Workers Compensation Litigation And
    The Workers Compensation Litigation Industry workers’ Compensation law firm

  23. Hey there! I know this is kind of off topic but I was wondering if you knew where
    I could find a captcha plugin for my comment form? I’m using the same blog platform
    as yours and I’m having problems finding one?
    Thanks a lot!

    Here is my web-site; Link Gacor Dor77

  24. Truck Wreck Attorney: What’s New? No One Is Talking About Truck Accident Lawyer

  25. Why users still make use of to read news papers when in this technological
    globe all is presented on net?

  26. boy789表示:

    Wow, wonderful blog layout! How lengthy have you ever been blogging
    for? you made blogging look easy. The total look of your website is wonderful, as neatly as the content!

發佈留言

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