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,478,008 Responses

  1. Twyla Cockram表示:

    9 Lessons Your Parents Taught You About Asbestos Attorney Mesothelioma asbestos attorney (clashofcryptos.Trade)

  2. CharlesweiNd表示:

    Discovered an article that might catch your interest – don’t miss it! http://pika.listbb.ru/posting.php?mode=post&f=9

  3. I was suggested this blog by my cousin. I’m not sure whether this post is written by him as no one else know such detailed about my problem.
    You are amazing! Thanks!

  4. 10 Healthy Habits To Use Untreated ADHD In Adults treating adhd naturally

  5. One thing I have actually noticed is always that there are plenty of fallacies regarding the banking companies intentions whenever talking about property foreclosure. One delusion in particular is that often the bank desires your house. The bank wants your cash, not your property. They want the money they gave you together with interest. Preventing the bank will still only draw some sort of foreclosed conclusion. Thanks for your write-up.

  6. Adriangek表示:

    Мы продаем устройства для систем водоснабжения, отопления, канализации и мебель под сантехнику. Поможем создать пространство с комфортными для жизни условиями Смеситель для раковины GPD Gildo MLB165-K-S Хром Черный

  7. Philip表示:

    Ghost 2 Immobiliser: What Nobody Is Talking About ghost immobiliser tracker (Philip)

  8. Arlie Blair表示:

    Bandar Online Togel Tools To Improve Your Everyday Lifethe Only Bandar Online Togel Trick That Every Person Should Know bandar online togel (Rosie)

  9. Jim Parker表示:

    A Proficient Rant Concerning Mercedes-Benz Key Replacement replacement keys for mercedes

  10. Ӏ simply couldn’t leave y᧐ur site before suggestin that І really
    enjoyed the useual informatіоn a person supply f᧐r yоur visitors?Iѕ ցoing to
    ƅe agаin regularly to check up ᧐n new posts

    mү website bocoran rtp slot

  11. Alex Ehrhart表示:

    How To Know The Window Handles That’s Right For You locking Window handle

  12. Top Entertainment In La Tania 유흥; zenwriting.net,

  13. telegra.ph表示:

    See What Fresh Ground Arabica Coffee Beans Tricks The Celebs Are Using ground arabica
    coffee beans (telegra.ph)

  14. 24 Hours To Improving Cheap Under Counter Fridge cheap refridgerator (pitts-kemp-2.blogbright.Net)

  15. 10 Misconceptions Your Boss Has About Toto Website 토토사이트 순위

  16. 20 Fun Details About Private Psychiatrist London Private Psychiatrist Cornwall

  17. 20 Tools That Will Make You More Efficient With Sprt Toto 4d 안전놀이터

  18. 10 Apps That Can Help You Control Your Physiological Symptoms Of Depression Psychological Signs Of Being Depressed

  19. ErnieTuh表示:

    Encountered a unique article – be sure to take a look and see for yourself https://драконь.рф/forum/topic.php?forum=6&topic=2295

  20. Mesothelioma, a cancerous growth that occurs in the organs’ linings, such as the abdomen and lungs (pleura), is caused by asbestos exposure.It’s usually caused by exposure to asbestos legal – Dominic,, a class of minerals made of microscopic fibres.

  21. 16 Facebook Pages You Must Follow For French Style Fridge Marketers french door fridge non plumbed (Cliff)

  22. 14 Smart Ways To Spend Your Extra Money Mini Cooper Replacement Key Budget mini Car key programming

  23. telegra.ph表示:

    Five Killer Quora Answers To Fridge Freezer Retro Cream fridge freezer retro (telegra.ph)

  24. Could Clitoris Vibrators Be The Key To Dealing With 2023?

    best Clitoris vibrators

  25. I think this is among the most significant information for me.

    And i am glad reading your article. But wanna remark on few general things, The website
    style is ideal, the articles is really nice : D. Good job, cheers

  26. 10 Life Lessons We Can Take From ADHD Private Diagnosis Private adhd Assessment Birmingham

  27. Brian Headlam表示:

    30 Inspirational Quotes About Tilt And Turn Window Tilt And Turn Window Repair

  28. 7 Small Changes You Can Make That’ll Make An Enormous Difference To Your Fleshlights Best Best rated fleshlight (https://golden-seal-fptjcx.mystrikingly.com)

  29. Appreciate it, Lots of content.

發佈留言

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