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,232,677 Responses

  1. WilliamRhype表示:

    https://nolvadex.life/# tamoxifen rash

  2. WilliamRhype表示:

    https://ciprofloxacin.tech/# cipro ciprofloxacin

  3. RandallTaulp表示:

    buying generic propecia no prescription: cheap propecia without prescription – get cheap propecia without dr prescription

  4. What’s The Current Job Market For Locksmiths Near
    Me For Car Professionals Like? Locksmiths Near Me For Car

  5. See What Double Glazed Windows Near Me Tricks The Celebs Are Utilizing double glazed windows Near me (http://fpcom.co.kr)

  6. Davidtes表示:

    cytotec buy online usa cytotec abortion pill cytotec pills buy online

  7. highwave.Kr表示:

    Undeniable Proof That You Need Replace Window Handle replacement Window handle [highwave.Kr]

  8. Davidtes表示:

    lisinopril 20 mg tablet price lisinopril 5mg cost can i order lisinopril over the counter

  9. Greetings from Florida! I’m bored to death at work so I decided
    to check out your blog on my iphone during lunch break.
    I love the information you present here and can’t wait to take a look when I get home.
    I’m amazed at how quick your blog loaded on my mobile ..
    I’m not even using WIFI, just 3G .. Anyways, wonderful blog!

  10. The 10 Most Terrifying Things About Double Glazing Company Near Me double glazing company Near me

  11. window repair表示:

    Guide To Window Repair: The Intermediate Guide For Window Repair window repair

  12. RandallTaulp表示:

    lisinopril 3760: price of zestril – 2 lisinopril

  13. RandallTaulp表示:

    buy nolvadex online: tamoxifen cost – who should take tamoxifen

  14. 5 Killer Quora Answers To Sash Window Repair window repair (http://www.cddc.co.Kr)

  15. Davidtes表示:

    cipro online no prescription in the usa cipro pharmacy where can i buy cipro online

  16. WilliamRhype表示:

    http://ciprofloxacin.tech/# ciprofloxacin 500mg buy online

  17. The Ultimate Guide To Replacement Windows Leeds Upvc window Repairs leeds

  18. One Key Trick Everybody Should Know The One Mercedes Key Trick
    Every Person Should Be Able To mercedes Car key Replacement

  19. 4 Dirty Little Tips About Best 18-Wheeler Accident Lawyer Industry Best 18-Wheeler Accident Lawyer Industry 18 Wheeler Accident

  20. Привет всем! Рад присоединиться к обсуждению.
    Я являюсь менеджером на портале, который
    специализируется на поставке планкена.
    У нас есть отличный планкен, который
    прекрасно подойдет для любого строительного проекта.

    В нашем ассортименте вы найдете широкий выбор планкена, включая планкен из лиственницы.
    Мы гарантируем, что вы все будут рады качеством нашего ассортимента.
    Спасибо за ваше внимание.
    Если у вас есть вопросы, я готов ответить.

  21. 20 Things That Only The Most Devoted Double
    Glazing Repair Leeds Fans Understand window repairs leeds

  22. 9 Lessons Your Parents Taught You About Couches On Sale Couches on sale

  23. How Much Can Railroad Injuries Lawyer Experts Earn? Railroad Injuries Lawsuit

  24. 20 Tools That Will Make You More Effective At Locksmith For Cars locksmith for cars near me

  25. RandallTaulp表示:

    tamoxifen medication: tamoxifen moa – nolvadex 10mg

  26. WilliamRhype表示:

    http://finasteride.store/# buying cheap propecia without a prescription

  27. case falchion表示:

    11 “Faux Pas” That Are Actually Acceptable To Make With Your CSGO Open Cases Sites
    case falchion

發佈留言

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