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,196,811 Responses

  1. I really like it when people come together and share ideas.
    Great website, keep it up!

  2. Scottnaigh表示:

    Find the latest information on Khabib Nurmagomedov https://khabib-nurmagomedov.uz news and fights. Check out articles and videos detailing Khabib UFC career, interviews, wins, and biography.

  3. Komentari su kao mapiranje puta – pomazu ti da se ne izgubis.
    Auto brend Cruze je popularan medu porodicama.
    Auto mi je toliko star da mu je originalna boja samo uspomena.

  4. Sherri表示:

    10 Things That Everyone Is Misinformed About Attorney For Asbestos Sherri

  5. Hey there! Do you know if they make any plugins to safeguard against hackers?

    I’m kinda paranoid about losing everything I’ve worked hard on. Any recommendations?

  6. Приветствую. Может кто знает, где почитать полезные статьи о недвижимости? Пока нашел https://utc96.ru

  7. d-rev.org lua dao nguoi choi dam me ca do bong da

  8. zackfoxworth表示:

    What Is The Fold Treadmill Term And How To Make
    Use Of It zackfoxworth

  9. eugosto.pt表示:

    You’ll Never Be Able To Figure Out This Upvc Door Doctor Near Me’s
    Tricks upvc door doctor (eugosto.pt)

  10. When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each
    time a comment is added I get four emails with the same comment.
    Is there any way you can remove me from that service? Thank you!

  11. 836614表示:

    10 Pets-Related Meetups You Should Attend 836614

  12. 3222914.xyz表示:

    15 Amazing Facts About Table Top Freezer That You’d Never Been Educated About
    3222914.xyz

  13. EverettFak表示:

    Прокат и аренда автомобилей https://autorent.by в Минске 2019-2022. Сутки от 35 руб.

  14. Medication information sheet. Drug Class.
    how can i get actos without prescription
    Everything news about drugs. Get here.

  15. EarnestAvada表示:

    Hello excellent blog! Does running a blog like this take a great deal of work? I have virtually no understanding of coding but I had been hoping to start my own blog soon. Anyhow, if you have any ideas or techniques for new blog owners please share. I know this is off subject however I just had to ask. Appreciate it!
    ggbet login

  16. eddafay.top表示:

    Five Things Everyone Makes Up On The Subject Of Bunk Bed For Sale eddafay.top

  17. Fantastic blog you have here but I was curious if you
    knew of any user discussion forums that cover the same topics talked
    about here? I’d really love to be a part of community where
    I can get feed-back from other experienced people that share the same
    interest. If you have any recommendations, please let me
    know. Kudos!

  18. Wonderful blog! I found it while searching on Yahoo News.

    Do you have any suggestions on how to get listed in Yahoo News?
    I’ve been trying for a while but I never seem to get there!
    Many thanks

  19. Superb blog you have here but I was curious about if you knew of any forums that
    cover the same topics talked about here? I’d really
    love to be a part of group where I can get responses from
    other experienced individuals that share the same interest.

    If you have any recommendations, please let me know. Thanks!

  20. Danielhom表示:

    In a world where communication is key, having a reliable phone number is essential for both personal and business interactions. However, not everyone needs a permanent number, especially when privacy, convenience, and flexibility are at stake https://jack-news.de/online-sms-empfang-in-deutschland-ihre-komplette-anleitung/

  21. Quick Things To Consider Playing At The Online Casino 프라그마틱 사이트

  22. Internet Marketing – 5 Platinum Fundamentals For Riches 검색엔진최적화 마케팅 (amybutlerlinens.com)

  23. Meds information. Effects of Drug Abuse.
    where buy cheap zanaflex pill
    Best information about drug. Get here.

  24. Can you tell us more about this? I’d love to find out more details.

發佈留言

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