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,260,548 Responses

  1. Sean White表示:

    몸캠피싱에 대해 잘 알려주셔서 감사합니다. 저희 몸캠피싱 에서도 이와 관련된 다양한 정보를 제공하고 있어요

  2. Jamesdiure表示:

    пин ап кз: pinup-kazi.kz – pinup

  3. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали сервисный центр huawei, можете посмотреть на сайте: сервисный центр huawei
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  4. Jamesdiure表示:

    pinup: pinup-kazi.kz – pinup kazi

  5. Howdy, i read your blog occasionally and i own a similar one and i
    was just wondering if you get a lot of spam comments?
    If so how do you reduce it, any plugin or anything you can advise?

    I get so much lately it’s driving me crazy so any support
    is very much appreciated.

  6. you are truly a just right webmaster. The website loading velocity
    is incredible. It seems that you’re doing any distinctive trick.
    Moreover, The contents are masterpiece. you’ve done a wonderful
    activity on this matter!

  7. DarioTob表示:

    вавада онлайн казино: вавада казино онлайн – вавада онлайн казино

  8. What’s The Current Job Market For Door Lock Replacement
    Near Me Professionals? door lock replacement near me

  9. This post is priceless. When can I find out more?

  10. memek表示:

    whoah this weblog is magnificent i love reading your posts.
    Keep up the good work! You understand, lots of people
    are looking round for this info, you can help them greatly.

  11. wrapfolie voor keukenkastjes

    hey there and thank you for your information – I have definitely
    picked up anything new from right here. I did however expertise several technical
    issues using this website, as I experienced to reload the web
    site lots of times previous to I could get it to load
    correctly. I had been wondering if your web hosting is OK?
    Not that I am complaining, but sluggish loading instances times
    will sometimes affect your placement in google and could damage your
    high-quality score if ads and marketing with Adwords. Anyway I am
    adding this RSS to my email and can look out for a lot more of your respective fascinating content.
    Ensure that you update this again soon.

  12. What’s The Job Market For Accident Lawyer Near Me Professionals Like?
    Accident Injury Law Firm

  13. Elsie Hogan表示:

    Passion exactly how laminate can mimic the look of real wood without breaking the financial institution! tile stores near me

  14. DarioTob表示:

    пин ап вход: pinup-kazi.ru – pinup kazi

  15. Appreciation to my father who stated to me concerning
    this website, this web site is genuinely awesome.

    Here is my page realtor in volusia county

  16. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали сервисный центр huawei в москве, можете посмотреть на сайте: официальный сервисный центр huawei
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  17. It is the best time to make some plans for the future and it’s time to be happy.
    I have read this post and if I could I want to suggest you some interesting things
    or tips. Maybe you can write next articles referring to
    this article. I desire to read even more things about it!

  18. Great article! We will be linking to this great post on our site.
    Keep up the great writing.

  19. Zac表示:

    11 “Faux Pas” That Are Actually OK To Create Using Your Asbestos
    Litigation Cases asbestos lawsuit – Zac,

  20. 밤문화表示:

    Adult Entertainment 밤문화

  21. I just like the helpful info you provide to your articles.
    I’ll bookmark your blog and test once more here regularly.
    I am fairly sure I’ll be told a lot of new stuff proper right
    here! Good luck for the following!

發佈留言

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