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

  1. Markdob表示:

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

  2. Ее услугами пользуются немецкие, итальянские, хорватские, латвийские, белорусские и румынские поклонники азартных развлечений.

  3. the answer is of course, “https://bookcrossing.ru/forum/topic/171936” is negative. But is is this investment in coming of your offspring?

  4. Markdob表示:

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

  5. Узнай все о операция исправление перегородки носаискривление носовой перегородки операция цена

  6. Markdob表示:

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

  7. BernardMop表示:

    ivermectin goodrx cheapest Ivermectin ivermectin lotion 0.5

  8. BrandenSlomy表示:

    where can i buy clomid prices: clomid rex pharm – can i purchase clomid price

  9. Hi there, this weekend is fastidious in support of me, for the reason that this moment i
    am reading this fantastic informative piece of
    writing here at my residence.

  10. Because the admin of this web site is working, no doubt very shortly it will be well-known, due to
    its quality contents.

  11. Nikefut表示:

    tor darknet best darknet markets https://darknetmarketstore.com/

  12. Furthermore, your body paragraphs don’t every talk about separate subjects, like “political campaigns” and “public well being.” Instead they support totally different factors in your argument.

  13. Nice blog here! Also your web site loads up fast!

    What host are you using? Can I get your affiliate link to your
    host? I wish my website loaded up as fast as yours
    lol

    Here is my web-site: فروشگاه آلات موسیقی ساز آرت

  14. AlbertDuM表示:

    buy plavix: PlavixClo Best Price – Plavix generic price

  15. bets10 giriş表示:

    Hi, I do believe your site could possibly be
    having browser compatibility problems. Whenever I take a look
    at your website in Safari, it looks fine but when opening in Internet Explorer,
    it’s got some overlapping issues. I simply wanted to provide you with a quick heads up!
    Other than that, excellent blog!

  16. BernardMop表示:

    Lisinopril 1st lisinopril1st lisinopril1st

  17. Markdob表示:

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

  18. BrandenSlomy表示:

    buy prednisone without a prescription: buy prednisone 40 mg – cortisol prednisone

  19. Markdob表示:

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

  20. BrandenSlomy表示:

    order generic clomid online: cheap clomid – where can i buy clomid without prescription

  21. An impressive share! I’ve just forwarded this onto a colleague who had been conducting a little research on this.
    And he in fact bought me dinner due to the fact that I discovered it for him…
    lol. So let me reword this…. Thanks for the meal!!

    But yeah, thanks for spending time to talk about this topic
    here on your internet site.

  22. Welⅼ, iѕn’t tһаt juѕt lovely? A Catholic ԝith “SJ” аfter theiг namе is
    respected becаᥙse it means tһey are
    a memƅer of tһe Society of Jesus, also know
    Reaԁ more

    Catholicism

    +1

    When waѕ oг wikl Easter bee on April 18?

    AskeԀ byy Wiki Useг

    In the yearѕ from 1875 to 2124, Easter haѕ appeared (᧐r will ɑppear) оn Аpril 18th in tһe Western Church оn tһe folloing yearѕ: 1897, 1954,1965, 1976, 2049, 2
    Read moгe

    Catholicism

    +2

    What is tһe meaning of ‘excelsis’?

    Αsked bу Wiki User

    “Excelsis” is a Latin term thаt means “high” or “lofty.”
    It iis often used in phrases likе “Gloria in excelsis Deo,” whic
    Read more

    Christianity

    +1

    What churches came directly οut οf the Catholic Church?

    Ꭺsked by Wikii Useг

    Oh, dude, like а bunch of churches split off from the Catholic Church ߋѵeг tһe years.

    You’ve gott tһe Eastern Orthodox Church,
    tһe Protestant churches, and even
    Reɑd mоre

    Catholicism

    +2

    Hoԝ mucһ ⅾoes ɑ cogiuc bishop mаke inn salary?

    Αsked by Wiki Usеr

    Thhe salary of a COGIC (Church ⲟf Godd іn Christ) bishop can vary
    widely depending օn factors suⅽh aѕ the size and location of the church, tһе bishop’s level оf e
    Read more

    Catholicism

    Ԝhich is thе ordinary ᧐f the Roman Catholic Mass?

    Αsked by Wiki User

    Thee mass texts tһat arе recited every day

    Feell free tto surf tߋ my web page :: ราคา iqos

  23. продамус промокод скидка на подключение https://rubiz.forum.cool/viewtopic.php?id=3874#p13 .

  24. BernardMop表示:

    cytotec buy online usa cheapest cytotec purchase cytotec

  25. AlbertDuM表示:

    stromectol canada: generic Stromectol – ivermectin 4 tablets price

  26. An outstanding share! I have just forwarded this onto a co-worker who had been doing a little research on this.

    And he in fact ordered me breakfast simply because
    I found it for him… lol. So let me reword this…. Thanks for the meal!!
    But yeah, thanx for spending some time to discuss this matter here on your website.

  27. AlbertDuM表示:

    cytotec abortion pill: cheapest cytotec – buy cytotec in usa

發佈留言

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