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,247,652 Responses

  1. BernardMop表示:

    ivermectin 12 mg inverfast.com stromectol 12mg online

  2. Hi there, the whole thing is going nicely here and ofcourse every one
    is sharing information, that’s actually excellent, keep up writing.

  3. Your style is so unique in comparison to other people
    I’ve read stuff from. Many thanks for posting when you
    have the opportunity, Guess I’ll just book mark this page.

  4. Stephenideox表示:

    Бесплатный информационный сервис, предоставляющий контент и справочную информацию о инвестировании.
    показатели окупаемости инвестиций

  5. BernardMop表示:

    п»їplavix generic cheapest plavix Cost of Plavix without insurance

  6. AlbertDuM表示:

    buy Lisinopril online: lisinopril1st – lisinopril1st

  7. A片表示:

    Hey there! This post couldn’t be written any better! Reading
    this post reminds me of my previous room mate! He always
    kept talking about this. I will forward this page to
    him. Fairly certain he will have a good read.
    Many thanks for sharing!

    Here is my website – A片

  8. Archie Holl表示:

    Land for own use or investment

  9. bocil sange表示:

    Someone necessarily lend a hand to make seriously articles
    I’d state. That is the very first time I frequented your website page and thus
    far? I amazed with the analysis you made to make this actual submit incredible.
    Fantastic task!

  10. rtp slot live表示:

    Hi, i read your blog from time to time and i own a similar one and i was just wondering if you get a lot of spam remarks?
    If so how do you stop it, any plugin or anything you can suggest?
    I get so much lately it’s driving me crazy so any support is very much appreciated.

  11. Do you mind if I quote a few of your posts as long as I provide credit and sources back
    to your weblog? My blog is in the exact same niche as yours and my
    visitors would really benefit from a lot of the information you provide here.
    Please let me know if this ok with you. Many thanks!

  12. google表示:

    At this time I am ready to do my breakfast, when having my breakfast coming again to read further news.

  13. Outstanding post however , I was wanting to know if you could write
    a litte more on this subject? I’d be very grateful if
    you could elaborate a little bit more. Thank you!

  14. Artie Pengra表示:

    Residential Land become limited

  15. Jessetor表示:

    Использование программного обеспечения вроде Хрумера для массового размещения текстов может рассматриваться как нарушение правил большинства платформ и поисковых систем. Такие действия могут повлечь за собой санкции и блокировку аккаунта. Я настоятельно рекомендую использовать легальные и этичные методы продвижения ваших материалов.
    Заказать прогон хрумером и гса можно у нас по адресу телеграмм логин @pokras7777 либо в телеграмм чате —-> https://t.me/+HFxk5vlUvGEzM2Zi так же у нас есть скайп логин pokras7777 и групаппа присаединяйтесь !!!!

  16. Hey there! Do you use Twitter? I’d like to follow you if
    that would be okay. I’m absolutely enjoying your blog and look forward to new updates.

  17. вывод из запоя в стационаре анонимно http://www.dexanet.ukrbb.net/viewtopic.php?f=14&t=20393 .

  18. Emilie Bryan表示:

    It’s always a hassle when your phone breaks, but finding a trustworthy repair shop makes all the difference. I recommend visiting iphone screen repair for some fantastic resources on phone repairs

  19. BernardMop表示:

    buy cytotec online fast delivery cytpremium buy cytotec over the counter

  20. Cole Frazier表示:

    I these days had my display changed at a smartphone restore store in North Lake phone repair shop

發佈留言

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