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,766 Responses

  1. BrandenSlomy表示:

    where to buy amoxicillin pharmacy: com pharm – purchase amoxicillin 500 mg

  2. Eligibility criteria for assisted residing in Jennings, LA can differ from one facility to another, however usually, people who can benefit from assisted residing are seniors who require help with ADLs, treatment administration, or different day by day duties, however don’t need 24-hour nursing care supplied by a nursing residence.

  3. Ida Howard表示:

    The manner you’ve got defined lots of hair treatments found out in salons is awfully informative; this is massive to be aware of what choices are plausible before entering into! Explore additional particulars at hair dresser

  4. вывод из запоя в стационаре анонимно superjackson.ukrbb.net/viewtopic.php?f=28&t=9734 .

  5. Blakesmema表示:

    https://shth.ru/ — Решения для обустройства кухни вашей мечты.

  6. Quality content is the crucial to attract the visitors to go to see
    the web page, that’s what this web site is providing.

  7. real sexdolls表示:

    17 Signs You Are Working With Cheap Realistic Sex Doll
    real sexdolls

  8. Does your site have a contact page? I’m having a tough time locating it but, I’d like to send
    you an e-mail. I’ve got some ideas for your
    blog you might be interested in hearing. Either way, great site
    and I look forward to seeing it grow over time.

    my web blog – free suga pro reviews

  9. pursvive表示:

    Hey There. I found your blog using msn. This is a very well written article.
    I will make sure to bookmark it and come back to read more of your useful info.
    Thanks for the post. I will definitely comeback.

    Check out my web site :: pursvive

  10. Markdob表示:

    Всем привет! Может кто знает, где почитатьразные статьи о недвижимости? Пока нашел – https://unnaty.ru

  11. BernardMop表示:

    buy Clopidogrel over the counter buy Plavix Clo buy plavix

  12. Markdob表示:

    Всем привет! Может кто знает, где найтиразные статьи о недвижимости? Сейчас читаю – https://unnaty.ru

  13. Main profile表示:

    It’s in fact very difficult in this busy life to listen news on TV, therefore I just use the web for
    that reason, and get the hottest news.

  14. Markdob表示:

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

  15. I’m not sure why but this website is loading extremely slow for me.
    Is anyone else having this problem or is it a problem on my end?

    I’ll check back later on and see if the problem still exists.

  16. Markdob表示:

    Приветствую. Подскажите, где почитатьразные статьи о недвижимости? Сейчас читаю – https://unnaty.ru

  17. Nikefut表示:

    dark web sites links dark web market list dark web search engines

  18. My brother suggested I might like this web site.
    He used to be entirely right. This put up truly made my day.
    You cann’t imagine just how a lot time I had
    spent for this info! Thanks!

  19. GavinGen表示:

    Access drug facts. Latest pill updates.
    imitrex intermediates
    Access medication details. Medication guide available.

  20. Very quickly this site will be famous amid all blog visitors, due to it’s good articles or reviews

  21. I’ve read a few good stuff here. Definitely price bookmarking for revisiting.
    I surprise how so much effort you put to make one of these great informative web site.

  22. Georgina表示:

    One Of The Most Untrue Advices We’ve Ever Been Given About Mesothelioma Attorney mesothelioma lawsuits (Georgina)

發佈留言

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