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,230,735 Responses

  1. savefrom表示:

    İşlerinizin artması için düzenli olarak fotoğraf ve video paylaşmanızı bekleriz.

  2. Тут можно преобрести сейфы от пожара сейф противопожарный

  3. yxhsm.net表示:

    20 Best Tweets Of All Time About Trucking Accident Attorneys trucking accidents attorneys (yxhsm.net)

  4. One Pram Success Story You’ll Never Believe Pram store near me

  5. 14 Common Misconceptions About Mystery Boxes open mystery boxes online

  6. 9 Lessons Your Parents Taught You About French Door Style Fridge Freezer french door fridge without water dispenser

  7. I know this if off topic but I’m looking into starting my own blog and was wondering what all is required to get set up?
    I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very web smart so I’m not 100% sure.

    Any recommendations or advice would be greatly appreciated.
    Cheers

  8. 9 Things Your Parents Teach You About Coffee Beans
    And Grinder coffee Beans and grinder

  9. Sazrwdy表示:

    Удивительно, но купить диплом кандидата наук оказалось не так сложно
    school97.ru/vesti20/index.php?PAGE_NAME=profile_view&UID=214974

  10. DwightDAURI表示:

    Access medication facts. Drug trends described.
    pharmacy online
    Pill essentials explained. Access drug details.

  11. How To Tell If You’re In The Right Place To Go After Driving License A1 na ile Zabierają prawo jazdy
    za alkohol 1 promil (http://www.google.co.zm)

  12. Do you have any video of that? I’d like to find out more details.

    https://w3.livetogelsydney.icu/

  13. 10 Citroen C1 Spare Key Cost Tricks All Experts Recommend citroen relay replacement key

  14. Triangle Billiards & Bar Stools
    1471 Nisson Ɍd, Tustin,
    CᎪ 92780, United Statеs
    +17147715380
    Billiard Table Restoration Checklist

  15. ClydePab表示:

    slot oyunlar?: en kazancl? slot oyunlar? – slot siteleri

  16. Sazrxyn表示:

    Как официально купить диплом вуза с упрощенным обучением в Москве
    forum.mbprinteddroids.com/showthread.php?tid=26152

  17. Тут можно преобрести сейф огнестойкий цена сейф огнеупорный купить

  18. See What Situstoto Slot Tricks The Celebs Are Utilizing Situstoto slot

  19. The Best Sex Toys Couples Tricks To Change Your
    Life best sex Toys couples

  20. 20 Insightful Quotes About Rooms To Go Sofa Sale small sofas for sale

  21. LarryCoell表示:

    Canl? Casino Siteleri Casino Siteleri guvenilir casino siteleri

  22. asbestos claim victims can receive compensation for future and past
    medical expenses as well as lost wages, suffering
    and other damages. The amount of compensation is contingent on the individual circumstances.

  23. Тут можно преобрести огнестойкие сейфы цена сейф огнестойкий цена

  24. Howdy! I’m at work browsing your blog from my new
    iphone 4! Just wanted to say I love reading through your
    blog and look forward to all your posts! Carry on the superb work!

    https://livetaipei2.ambarita.org/

  25. 9 Lessons Your Parents Taught You About Cheapest Automatic Folding Mobility Scooter Cheapest automatic folding Mobility Scooter

  26. 9 Things Your Parents Teach You About Cost Of Replacing Misted Double Glazing Units Cost of replacing misted double glazing units

發佈留言

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