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,672,468 Responses

  1. Hey there would you mind sharing which blog platform you’re using?

    I’m planning to start my own blog soon but I’m having a hard time
    selecting 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 My apologies for getting off-topic but I had to ask!

  2. Diplomi_jsOl表示:

    купить дипломы о высшем образовании москва купить дипломы о высшем образовании москва .

  3. Cazrkxx表示:

    Удивительно, но купить диплом кандидата наук оказалось не так сложно
    russianecuador.com/forum/member.php?u=13207

  4. Jorgeagopy表示:

    medication from mexico pharmacy: mexican drugs – medicine in mexico pharmacies

  5. Jamesses表示:

    Познакомьтесь не без; нашим проф коллективом, яже образовывает уникальную этажерка, воплощая ваши грезы в реальность http://www.cehitae2kuhnishki.ru/.

  6. Williamagric表示:

    ed drug comparison http://indianpharm24.pro/# cheapest online pharmacy india

  7. Williamagric表示:

    male erectile dysfunction https://pharm24.pro/# vitality ed pills

  8. Diplomi_vgOl表示:

    купить диплом логопеда diplomdarom.ru .

  9. Jorgeagopy表示:

    best india pharmacy: indian pharm 24 – india pharmacy mail order

  10. DevonPhack表示:

    http://mexicanpharm24.cheap/# buying prescription drugs in mexico
    ed pills online pharmacy

  11. Hello there! I could have sworn I’ve been to this blog before but after browsing through some
    of the post I realized it’s new to me. Nonetheless, I’m definitely
    delighted I found it and I’ll be book-marking and checking back often!

  12. It’s The Mesothelioma Law Case Study You’ll Never Forget Mesothelioma litigation

  13. Williamagric表示:

    new ed treatments http://mexicanpharm24.cheap/# mexican pharmaceuticals online

  14. BrandonSaisy表示:

    cvs prescription prices without insurance: buy drugs – best ed pill

  15. Сервисный центр предлагает ремонт zte blade a601 в петербурге ремонт zte blade a601 цены

  16. A How-To Guide For L Shaped Small Sofa From Beginning To End l shaped couch recliner

  17. 5 Bed Settee For Sale Tips From The Pros Sofas For Sale London (http://Yerliakor.Com/User/Houseage55)

  18. 10 Things You Learned In Kindergarden Which Will Aid
    You In Obtaining Titration For ADHD adhd Medication titration

  19. DevonPhack表示:

    http://indianpharm24.pro/# indian pharmacy paypal
    dog antibiotics without vet prescription

  20. slot gacor表示:

    I have to thank you for the efforts you’ve put in writing this blog.
    I’m hoping to check out the same high-grade blog posts by you in the future as well.
    In truth, your creative writing abilities has motivated me to get my very own website now 😉

  21. Five Killer Quora Answers To Couches L Shape Couches L Shape

  22. Chad表示:

    Sex Machines For Sale: The History Of Sex Machines For
    Sale In 10 Milestones men sex machines (Chad)

  23. Williamagric表示:

    how to help ed http://mexicanpharm24.cheap/# buying from online mexican pharmacy

  24. What’s The Job Market For Reclining Sectional With Chaise Professionals Like?
    Reclining Sectional With Chaise

  25. How To Explain Shop Anal Sex Toy To A 5-Year-Old anal toy for her

  26. Rolandofiz表示:

    wawada

  27. Сервисный центр предлагает замена процессора msi a6200 замена дсплея msi a6200

發佈回覆給「DevonPhack」的留言 取消回覆

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