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,364,918 Responses

  1. Drugs information for patients. What side effects can this medication cause?
    where to buy cheap bactrim
    Actual what you want to know about meds. Read information now.

  2. DanielAbice表示:

    https://amoxstar.com/# order amoxicillin online uk

  3. SamuelBix表示:

    2.5 mg prednisone daily: prednisone 10mg tablet price – price for 15 prednisone

  4. kvtoto login表示:

    An outstanding share! I’ve just forwarded this
    onto a colleague who was doing a little research on this.
    And he actually bought me lunch simply because I found it for him…
    lol. So allow me to reword this…. Thank YOU for the meal!!
    But yeah, thanx for spending the time to talk about this subject here on your web page.

  5. Glenn Hall表示:

    Education robotics offers students the opportunity to develop skills that are highly sought-after in the job market, such as coding and problem-solving. Find out how εργαστηρια ρομποτικης can support your students’ growth

  6. Lou Brooks表示:

    If you’ve been in a car accident, hiring a knowledgeable attorney can make all the difference injury lawyer near me

  7. Altongrept表示:

    СЗЗ (санитарно защитная зона) для промышленных предприятий в Москве и Московской области. Что нужно учесть при разработке проекта СЗЗ и на этапе согласования в органах надзора для обеспечения законной деятельности объекта НВОС https://vc.ru/u/3791103-infa-v-dele/1719864-chto-takoe-szz-i-kak-razrabotat-proekt-sanitarnoi-zony

  8. KennethPah表示:

    can i buy prednisone over the counter in usa prednisone 20mg online prednisone tablets 2.5 mg

  9. Light Roast Arabica Coffee Beans Tools To Ease Your Everyday Lifethe Only Light Roast Arabica Coffee Beans Trick That Every Person Must Learn Coffee Beans (https://Yogaasanas.Science)

  10. Wonderful blog! Do you have any helpful hints for
    aspiring writers? I’m hoping to start my own blog soon but I’m a
    little lost on everything. Would you advise starting with a free platform like WordPress or go
    for a paid option? There are so many options out there that I’m totally overwhelmed ..
    Any suggestions? Appreciate it!

  11. DanielAbice表示:

    http://cipharmdelivery.com/# ciprofloxacin mail online

  12. Nikefut表示:

    darknet drug links tor markets links tor market

  13. More Info表示:

    Link exchange is nothing else except it is only placing the other person’s weblog link on your
    page at suitable place and other person will also do same
    in favor of you.

  14. StephenDeery表示:

    This is really attention-grabbing, You are a very skilled blogger. I’ve joined your feed and stay up for looking for extra of your wonderful post. Also, I have shared your site in my social networks
    фильмы онлайн бесплатно

  15. atomic wallet表示:

    I love your blog.. very nice colors & theme. Did you make this website yourself or did
    you hire someone to do it for you? Plz answer back
    as I’m looking to construct my own blog and would like to know where u got this from.
    appreciate it

  16. Very informative article. For similar content, visit clip sex

  17. Здесь можно купить сейф для дома цена купить сейфы для дома

  18. Emilie Greene表示:

    This was a wonderful guide. Check out sex việt nam for more

  19. Lelia Dean表示:

    Wonderful tips! Find more at phim sex nhật bản

  20. Hilda Barnett表示:

    Well explained. Discover more at phim sex 2025

  21. Adele206表示:

    Nice blog. Found this while searching through

  22. Dennis Price表示:

    Thanks for the helpful article. More like this at phim sex trẻ em df99991

  23. Harry Simmons表示:

    I’ve learned so much about responsible waste disposal thanks to your post—time to check out dumpster rentals in Alamance

  24. RobertJar表示:

    how can i get cheap clomid price: clomid on pharm – can you buy clomid now

  25. Hi there! This blog post could not be written much better!

    Going through this post reminds me of my previous roommate!
    He continually kept talking about this. I will forward this information to him.
    Fairly certain he’ll have a good read. I appreciate you
    for sharing! http://Idesys.CO.Kr/bbs/board.php?bo_table=free&wr_id=95815

  26. Lhaneevige表示:

    Marvelous, what a webpage it is! This webpage provides helpful data to us, keep it up.
    смотреть кино онлайн

發佈留言

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