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,449,594 Responses

  1. I think everything published made a bunch of sense.
    But, think on this, suppose you typed a catchier post title?
    I am not saying your information is not good., but suppose you added a
    post title that makes people desire more? I mean JS 依照元素出現數量排序 – 馬老師 雲端研究室 is a little boring.
    You should glance at Yahoo’s front page and watch how they create news titles to get people to click.
    You might add a related video or a related pic or two to get people excited about what
    you’ve got to say. Just my opinion, it would make your blog a little bit more
    interesting.

  2. Brandonnot表示:

    Online pharmacy: Indian Cert Pharm – IndianCertPharm

  3. kypit 1s_gjor表示:

    купить 1с бухгалтерия купить купить 1с бухгалтерия купить .

  4. Brandonnot表示:

    mexico drug stores pharmacies: purple pharmacy mexico price list – mexican rx online

  5. CurtisBam表示:

    Indian pharmacy that ships to usa: Best online Indian pharmacy – Indian pharmacy international shipping

  6. Brandonnot表示:

    Mexican Easy Pharm: Mexican Easy Pharm – buying from online mexican pharmacy

  7. Brandonnot表示:

    online pharmacy india: Indian Cert Pharm – buy medicines online in india

  8. CurtisBam表示:

    canadian pharmacy online store: canadian pharmacy no scripts – drugs from canada

  9. Michaelallek表示:

    Виртуальные номера становятся все более популярными как среди частных пользователей, так и в бизнес-среде. Эти номера позволяют принимать звонки и SMS, а также использовать их для регистрации в различных сервисах без необходимости привязываться к физическому номеру телефона. Технология основывается на использовании IP-телефонии, что дает пользователю массу преимуществ по сравнению с традиционными номерами номер телефона Великобритании

  10. CurtisBam表示:

    best canadian online pharmacy reviews: Canadian Md Pharm – trusted canadian pharmacy

  11. Responsible For The ADHD Private Assessment Budget?
    12 Tips On How To Spend Your Money private adhd assessment stoke
    on trent, https://Maps.Google.hr,

  12. Drug prescribing information. What side effects?
    how to get generic bactrim without a prescription
    Everything news about drugs. Get here.

  13. Carrolleruck表示:

    https://mexicaneasypharm.com/# buying prescription drugs in mexico online
    canadian king pharmacy

  14. Brandonnot表示:

    Mexican Easy Pharm: Mexican Easy Pharm – medication from mexico pharmacy

  15. Brandonnot表示:

    canadian pharmacy prices: Canadian Md Pharm – canadian neighbor pharmacy

  16. Looking For Inspiration? Check Out Mystery Boxes mystery Box Online opening

  17. вывод из запоя в стационаре воронежа vyvod-iz-zapoya-v-stacionare-voronezh23.ru .

  18. DominicSpurl表示:

    заказать дизайнера интерьера квартиры дизайнер интерьера москва цены и работы

  19. Carrolleruck表示:

    https://indiancertpharm.com/# Best Indian pharmacy
    canadian pharmacy near me

  20. kypit 1s_juEn表示:

    программы фирмы 1с программы фирмы 1с .

  21. Sabine表示:

    See What Homeowner Gas Safety Certificate Tricks The Celebs Are Utilizing homeowner gas safety certificate (Sabine)

  22. Pills prescribing information. Generic Name.
    how can i get fluvoxamine tablets
    Everything news about pills. Get now.

  23. Τhanks for the marvelօuѕ ρosting! I genuinely enjoyed reading it, you cann be a gгeat
    authօr.I will remembег to bookmark yоur blog
    and definitely wilⅼ come back in thhe foreseeable future.
    І want to encourage yоu continue yߋur greаt job, have a nice evening!

    My sіte … bandung driver; https://usagi-wiki.com/index.php?title=Paket_Wisata_Bandung_1_Hari_Metropolis_Tour_Murah_2024,

  24. That is a really good tip particularly to those
    fresh to the blogosphere. Simple but very accurate info… Many thanks for sharing this one.
    A must read post!

  25. Molly表示:

    How To Prepare Your Casino Night Party Dealers 부산달리기 (Molly)

  26. kypit 1s_byor表示:

    настройка 1с бухгалтерии цена настройка 1с бухгалтерии цена .

  27. jinda55表示:

    Guest lineups for the Sunday news shows
    By ASSOCIATED PRESS

    Published: 23:27 GMT, 9 October 2015 | Updated: 23:
    27 GMT, 9 October 2015

    e-mail

    WASHINGTON (AP) — Guest lineups for the Sunday TV news shows:

    ABC’s “This Week” — Rep. Jason Chaffetz, R-Utah; Republican presidential candidate Bobby Jindal.

    ___

    NBC’s “Meet the Press” — Democratic presidential candidate Bernie
    Sanders; Reps. Charlie Dent, R-Pa., and Dave Brat, R-Va.

    ___

    CBS’ “Face the Nation” — Republican presidential candidates
    Ben Carson and Donald Trump; Rep. Mick Mulvaney, R-S.C.

    ___

    CNN’s “State of the Union” — Democratic presidential candidate
    Martin O’Malley; Reps. Tom Cole, R-Okla., Raul Labrador,
    R-Idaho, and Debbie Wasserman Schultz, D-Fla.

    ___

    “Fox News Sunday” — Rep. Jim Jordan, R-Ohio; former House Speaker Newt
    Gingrich, R-Ga.

發佈留言

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