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,365,544 Responses

  1. eb5 visa表示:

    What’s Happening i’m new to this, I stumbled upon this
    I’ve discovered It absolutely helpful and it has helped
    me out loads. I’m hoping to contribute & assist different customers like its
    aided me. Great job.

  2. StevenNub表示:

    prednisone 5 mg: raypharm – prednisone 10mg for sale

  3. Very good article. I will be facing some of these issues
    as well..

  4. Informative article, just what I wanted to find.

  5. What’s up i am kavin, its my first occasion to commenting anywhere, when i read this piece of writing i thought i could also
    create comment due to this sensible post.

  6. - lol edibles表示:

    Great delivery. Sound arguments. Keep up the amazing spirit.

  7. Medication prescribing information. Cautions.
    order generic fexofenadine
    All about medicines. Get information now.

  8. StevenNub表示:

    prednisone cost us: prednisone – prednisone 30 mg coupon

  9. Highly descriptive blog, I loved that a lot. Will there
    be a part 2?

  10. Dereketerm表示:

    prednisone 300mg: prednisone – prednisone 100 mg

  11. As interpretacoes dos sonhos mais populares dos livros mais populares sobre o sono
    Sonho de loja de penhores

    [url=http://nrp.i7.lt/index.php?/topic/896846-%E2%80%A2-iron-grate-bbq-co-closes-its-doors-after-8-years-of-service-wisn/page-4728#entry4037338]Sonha com um cao que morde o seu braco? Doeu e sangrou? Interpretacao de um sonho de acordo com diferentes livros de sonho[/url] [url=http://nrp.i7.lt/index.php?/topic/896846-%E2%80%A2-iron-grate-bbq-co-closes-its-doors-after-8-years-of-service-wisn/page-4529#entry4008116]Porque e que sonho com o kvass?[/url] [url=https://twiggandolive.com/2023/04/10/hello-world/#comment-19212]Sonho de loja de penhores[/url] [url=http://primaria.scortoasa.ro/component/k2/item/15-vestibulum-faucibus-mollis-tellus-massaa]Porque e que sonho com uma cruz partida?[/url] [url=http://vienna.ug/index.php?option=com_k2&view=item&id=13]Num sonho, apanhar coisas[/url] 93983f1

  12. LeonardKnism表示:

    tir92.ru/ – Воплощаем идеи в реальные кухни для вашего дома.

  13. Hi there colleagues, its enormous post on the topic of cultureand completely explained, keep it up all the time.

  14. Land use表示:

    My relatives all the time say that I am wasting my time here
    at web, but I know I am getting know-how daily by reading
    such pleasant articles.

  15. StevenNub表示:

    order amoxicillin uk: Amoxicillin for sale – generic amoxicillin

  16. Belle Austin表示:

    Thanks for the thorough article. Find more at https://gamehitclub.dev/

  17. BrandenSlomy表示:

    buy priligy: priligy – buy priligy max pharm

  18. spam site表示:

    Thanks for one’s marvelous posting! I genuinely enjoyed reading it, you’re a great author.I will remember to bookmark your
    blog and definitely will come back from now on. I want to encourage continue your great job, have a nice holiday weekend!

  19. Hi there to all, how is all, I think every one is getting more from this website, and your
    views are pleasant for new users.

  20. карниз для эркера настенный купить https://elektrokarniz495.ru .

  21. вызов нарколога на дом краснодар http://www.spilkuvannya.rolevaya.com/viewtopic.php?id=66 .

  22. Casino表示:

    Howdy! Would you mind if I share your blog with my facebook group?
    There’s a lot of folks that I think would really enjoy your content.
    Please let me know. Many thanks

  23. At this time it appears like WordPress is the top blogging platform out there right now.
    (from what I’ve read) Is that what you are using on your blog?

  24. An intriguing discussion is worth comment. I do think that you ought to
    publish more about this subject matter, it might
    not be a taboo matter but generally folks don’t speak about these
    topics. To the next! Kind regards!! https://www.Goodspeedcomputer.com/question/immigrating-to-canada-a-comprehensive-guide/

  25. Dereketerm表示:

    amoxicillin generic: Amoxicillin for sale – amoxicillin price without insurance

  26. forkpart.ru表示:

    На forkpart.ru выполняется ремонт двигателей погрузчиков, включая диагностику, замену неисправных узлов и профилактическое обслуживание. Мы понимаем, насколько важно поддерживать двигатель в рабочем состоянии, поэтому используем только качественные детали и проверенные методы. Наша команда обеспечивает точную диагностику и минимальные сроки ремонта, чтобы ваша техника не простаивала.

發佈留言

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