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,234,759 Responses

  1. With thanks, Fantastic stuff!

  2. aiporn.date表示:

    Aw, this was an extremely nice post. Finding the time and actual effort to produce a great
    article… but what can I say… I put things off a lot and don’t
    seem to get anything done.

  3. Hello, always i used to check webpage posts here in the early hours in the daylight, since i like to find out more and more.

  4. ClydePab表示:

    matadorbet bid: matadorbet giris – matadorbet bid

  5. KHALIS表示:

    I like looking through a post that will make people think.
    Also, thank you for allowing me to comment!

  6. LarryCoell表示:

    ultrabet tr online ultrabet yeni giris 1125 ultrabet tr online

  7. This website was… how do I say it? Relevant!! Finally
    I have found something that helped me. Appreciate it!

    https://datahk6d.one/

  8. What Is Private Assessment For ADHD’ History? History Of Private
    Assessment For ADHD private adult adhd assessment belfast [http-directory.com]

  9. See What Mobility Scooters On Road Or Pavement Tricks The Celebs Are Using mobility scooters on road or Pavement (brock-shields.blogbright.net)

  10. salon fit out表示:

    Good information Many thanks!

  11. Where Can You Get The Top Drip Coffee Pot Information? Dripping Coffee

  12. Trefndk表示:

    Как получить диплом техникума официально и без лишних проблем
    krasnozovodsk.flybb.ru/viewtopic.php?f=2&t=312

  13. Have you ever thought about adding a little bit more than just your articles?

    I mean, what you say is important and all. Nevertheless imagine
    if you added some great pictures or videos to give your posts more, “pop”!
    Your content is excellent but with images and videos, this blog could
    certainly be one of the most beneficial in its niche. Superb blog!

  14. My partner and I absolutely love your blog and find many of your post’s to be exactly I’m looking for.
    Would you offer guest writers to write content for you personally?
    I wouldn’t mind composing a post or elaborating on many of the subjects you write regarding here.
    Again, awesome web site!

    Review my webpage; สล็อต

  15. Trefcaf表示:

    Официальная покупка аттестата о среднем образовании в Москве и других городах

    forum.omnicomm.pro/index.php?action=post;board=20.0

  16. Trefsdq表示:

    Процесс получения диплома стоматолога: реально ли это сделать быстро?
    the-trifecta-network.mn.co/posts/69456340

  17. Hi there, just became aware of your blog through Google, and found that
    it is really informative. I am going to watch out for brussels.
    I’ll be grateful if you continue this in future. Numerous people will be benefited from
    your writing. Cheers!

  18. Why We Our Love For Bmw Replacement Key Cost (And You Should Also!)
    Bmw Key Program

  19. Derekfar表示:

    matadorbet bid: matadorbet – matadorbet

  20. Your method of explaining everything in this paragraph is genuinely good,
    all be capable of simply know it, Thanks a lot https://www.lescaledetente.com/cours-de-yoga-pilates/

  21. I was wondering if you ever considered changing the layout of your
    blog? Its very well written; I love what youve
    got to say. But maybe you could a little more in the way of content so people
    could connect with it better. Youve got an awful lot of text for
    only having one or 2 pictures. Maybe you could space it out
    better?

  22. Drugs information leaflet. Long-Term Effects.
    what is metformin sr
    Some information about pills. Get now.

  23. What Is What Are Anxiety Symptoms And Why Is Everyone Speakin’ About
    It? Crippling Anxiety Symptoms

  24. RobertBaf表示:

    Найдите надежное помещение для вашего дела! Коммерческая собственность для приобретения и аренды. Подробнее на сайте: https://homeakademia.ru

  25. best GFE表示:

    Hey! I know this is kind of off topic but I was wondering
    if you knew where I could get a captcha plugin for my comment form?

    I’m using the same blog platform as yours and I’m having problems finding one?
    Thanks a lot!

  26. Raina表示:

    1kg Coffee Beans Explained In Less Than 140 Characters 1kg coffee beans price (Raina)

  27. Sofa 2 Seater Fabric Tools To Make Your Daily Lifethe One Sofa 2 Seater Fabric Trick Every Individual Should
    Know sofa 2 seater fabric

  28. 3.13.251.167表示:

    How Much Do Top Rated Cots Experts Earn? Best Cots – 3.13.251.167,

發佈留言

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