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,229,929 Responses

  1. Diplomi_giMl表示:

    купить аттестат об окончании школы купить аттестат об окончании школы .

  2. naturally like your web-site however you need to test the spelling on quite a few of your posts.
    Several of them are rife with spelling problems and I in finding it very troublesome
    to tell the truth nevertheless I’ll certainly come back again.

  3. HassanbuifS表示:

    https://slot-tr.online/# slot oyunlar?
    deneme bonusu veren siteler betturkey

  4. Heya! I understand this is sort of off-topic however I had to ask.
    Does running a well-established blog like yours take a lot of
    work? I’m brand new to blogging but I do write in my diary
    everyday. I’d like to start a blog so I can share my experience and thoughts online.
    Please let me know if you have any suggestions or tips for new aspiring bloggers.
    Appreciate it!

  5. HassanbuifS表示:

    https://casinositeleri.win/# Casino Siteleri
    denemebonusuverensiteler.top

  6. Who Is The World’s Top Expert On Private Diagnosis For ADHD?
    Private Adhd Assessment Reading

  7. CarrollUnton表示:

    deneme bonusu veren siteler yeni https://casinositeleri.win/# Canl? Casino Siteleri

  8. Derekfar表示:

    slot tr online: az parayla cok kazandiran slot oyunlar? – slot tr online

  9. Hi there i am kavin, its my first occasion to commenting anyplace,
    when i read this post i thought i could also create comment due to this sensible piece of writing.

  10. Why The Fireplace Suites Electric Is Beneficial When COVID-19 Is In Session freestanding electric fireplace heater with mantel

  11. Your means of telling all in this piece of writing is really fastidious, all can without difficulty be aware of it, Thanks a lot.

    Here is my website … บาคาร่าออนไลน์

  12. 5 Killer Quora Answers On Best Electric Patio Heater
    Uk best electric patio heater uk

  13. Stephenideox表示:

    Погрузитесь в течение мир увеселений и увлекательных 3 сверху портале Любовь 28!
    юбилей

  14. telegra.ph表示:

    You’ll Be Unable To Guess Generalised Anxiety Disorder’s Secrets
    generalised anxiety disorder; telegra.ph,

  15. tg下载表示:

    有關如何下載和使用 Telegram中文版的更多信息,請訪問我們的外部博客鏈接: 飛機下載

  16. 10 Places That You Can Find Upvc Window And Door Repairs upvc sliding door repair near Me

  17. This is really attention-grabbing, You are an overly professional blogger.
    I’ve joined your rss feed and look ahead to in the hunt for more of your great post.

    Also, I’ve shared your website in my social networks

  18. You’ll Never Guess This Upvc Window Repairs Near Me’s Tricks upvc window repairs near Me

  19. tg中文表示:

    您想了解更多關於 Telegram 的中文版下載,設置和高級功能的更多信息嗎? 有關更詳細的說明和有用的建議,請單擊此處查看我們的外部博客鏈接: 电报

  20. Hey I know this is off topic but I was wondering if you knew
    of any widgets I could add to my blog that automatically tweet my newest twitter updates.

    I’ve been looking for a plug-in like this for quite some time and
    was hoping maybe you would have some experience with something like this.
    Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your
    new updates.

  21. If you or a loved one has been diagnosed with an asbestos-related illness you might be able to bring an asbestos lawsuit.
    A mesothelioma case lawyer will help you understand your options and start the process.

  22. LarryCoell表示:

    slot oyunlar? slot tr online az parayla cok kazandiran slot oyunlar?

  23. Derekfar表示:

    ultrabet yeni giris 1125: ultrabet bonus – ultrabet tr online

  24. Derekfar表示:

    ultrabet giris: ultrabet – ultrabet

  25. Тут можно преобрести оружейные сейфы и шкафы для охотничьего купить оружейный сейф цена

  26. It’s a pity you don’t have a donate button! I’d definitely donate
    to this superb blog! I guess for now i’ll settle for bookmarking and adding your RSS feed to my Google account.
    I look forward to fresh updates and will talk about this site with my Facebook group.
    Talk soon!

  27. 13 Things You Should Know About Hiring Car Accident Lawyers That You Might Not Have Known accident attorney car (https://Peatix.com/user/24101408)

  28. ClydePab表示:

    matadorbet bid: matadorbet bid – matadorbet.bid

  29. Hello, Neat post. There is a problem together with your web site in web explorer, could test this?
    IE still is the market leader and a large portion of folks will
    pass over your magnificent writing due to this problem.

發佈留言

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