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,370,429 Responses

  1. HeathZex表示:

    pharmacie en ligne france livraison belgique: Medicaments en ligne livres en 24h – pharmacie en ligne livraison europe

  2. Charlesrab表示:

    pharmacie en ligne fiable Medicaments en ligne livres en 24h pharmacie en ligne livraison europe

  3. HeathZex表示:

    pharmacie en ligne france livraison internationale: cialis generique – vente de mГ©dicament en ligne

  4. HeathZex表示:

    Pharmacie sans ordonnance: Cialis sans ordonnance pas cher – pharmacie en ligne livraison europe

  5. aloha porn表示:

    Halo 3: ODST 2009 first-person shooter recreation developed by Bungie.
    Published by Microsoft Game Studios. The fifth installment within the Halo franchise as a side game,[1] it was launched on the
    Xbox 360 in September 2009. Players assume the roles of United Nations Space Command Marines, often called “Orbital Drop Shock Troopers” or ODSTs, throughout and
    after the occasions of Halo 2. In the sport’s campaign mode, gamers
    explore the ruined city of recent Mombasa to find what occurred to their lacking teammates within the midst of an alien invasion. Within the “Firefight” multiplayer possibility, gamers battle
    more and more difficult waves of enemies to attain factors and survive as long
    as possible; Halo three’s multiplayer is contained on a separate disc
    packaged with ODST.

  6. Charlesrab表示:

    Le gГ©nГ©rique de Viagra viagra en ligne Viagra sans ordonnance 24h suisse

  7. This design is incredible! You obviously know how to keep a
    reader amused. Between your wit and your videos,
    I was almost moved to start my own blog (well, almost…HaHa!) Wonderful job.
    I really enjoyed what you had to say, and more than that,
    how you presented it. Too cool!

  8. This text is invaluable. Where can I find out more?

  9. Stephengen表示:

    http://vgrsansordonnance.com/# Prix du Viagra en pharmacie en France

  10. 충청남도 유흥 메카 성정동에 위치한 천안노래방으로 놀러 오세요

  11. Профессиональный сервисный центр по ремонту принтеров в Москве.
    Мы предлагаем: сервисный центр принтеров
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  12. Charlesrab表示:

    Viagra homme prix en pharmacie sans ordonnance Sildenafil Viagra Le gГ©nГ©rique de Viagra

  13. Профессиональный сервисный центр по ремонту МФУ в Москве.
    Мы предлагаем: вызвать мастера по ремонту мфу
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  14. Stephengen表示:

    http://clssansordonnance.icu/# pharmacie en ligne france fiable

  15. What’s The Job Market For Togel Singapore Professionals
    Like? togel singapore – crews-pearce.federatedjournals.com

  16. Charlesrab表示:

    pharmacies en ligne certifiГ©es Cialis prix en pharmacie pharmacie en ligne fiable

  17. HeathZex表示:

    pharmacie en ligne france fiable: Cialis sans ordonnance pas cher – pharmacie en ligne avec ordonnance

  18. Hi there to all, how is all, I think every one is getting more from this website, and your views are fastidious
    for new visitors.

  19. HeathZex表示:

    Viagra homme sans prescription: viagra sans ordonnance – Viagra 100 mg sans ordonnance

  20. HeathZex表示:

    Achat mГ©dicament en ligne fiable: vente de mГ©dicament en ligne – vente de mГ©dicament en ligne

  21. 10 Tips For Getting The Most Value From Locksmith Cars
    locksmith for Car key near me

  22. 태백산의 정기를 강원도호빠에서 한 번 느껴 보실래요?

  23. HeathZex表示:

    pharmacie en ligne: Acheter Cialis – Pharmacie sans ordonnance

  24. Профессиональный сервисный центр по ремонту принтеров в Москве.
    Мы предлагаем: сколько стоит ремонт принтера
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  25. Hi, i think that i saw you visited my website so i
    came to “return the favor”.I’m attempting to find things
    to enhance my web site!I suppose its ok to use a few of your ideas!!

發佈留言

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