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,229,566 Responses

  1. Drug information leaflet. Long-Term Effects.
    hydroxyzine dihydrochloride structure
    Actual trends of medicament. Read information now.

  2. Bruceviomy表示:

    Ведь есть же десятки сервисов для номеров из других стран. А беларусские форумы огорожены, им подавай только их собственный картофель типа +375 купить номер США

  3. What NOT To Do In The Door Doctor Near Me Industry the door doctor near me

  4. CarrollUnton表示:

    deneme bonusu veren siteler yerliarama.org https://slot-tr.online/# slot siteleri

  5. Unquestionably believe that which you stated. Your favorite justification appeared to be on the internet the easiest thing to be aware of.
    I say to you, I definitely get irked while people consider worries
    that they just do not know about. You managed to hit the nail upon the top
    and defined out the whole thing without having side effect ,
    people can take a signal. Will likely be back to get more.
    Thanks

  6. 15 Things You Didn’t Know About Adult Adhd Assessment How To Get Assessed For Adhd

  7. Good post however I was wondering if you could write
    a litte more on this topic? I’d be very grateful if you could elaborate a little bit more.
    Cheers!

  8. 15 Best Asbestos Mesothelioma Bloggers You Should Follow Mesothelioma Lawyers

  9. ClydePab表示:

    en cok kazand?ran slot oyunlar?: slot tr online – az parayla cok kazandiran slot oyunlar?

  10. What’s The Current Job Market For U Shaped Leather
    Sectional Professionals? U Shaped Leather Sectional

  11. Stephenideox表示:

    Окунитесь в мир развлечений а также увлекательных историй сверху портале Любовь 28!
    инвестиции

  12. Тут можно преобрести купить сейф для ружья оружейные сейфы купить

  13. What’s The Current Job Market For Getting
    A New Car Key Cut Professionals? Getting A New Car Key Cut
    (Pediascape.Science)

  14. Currently it seems like Drupal is the top blogging platform available
    right now. (from what I’ve read) Is that what you’re using on your blog?

  15. Тут можно преобрести сейф пожаростойкий сейф москва огнестойкий купить

  16. Hey! I just wanted to ask if you ever have any trouble with
    hackers? My last blog (wordpress) was hacked
    and I ended up losing months of hard work due to
    no back up. Do you have any methods to prevent hackers? https://jimsusefultools.com/index.php/User:Marcelo61B

  17. Have you ever thought about including a little bit more than just your articles?

    I mean, what you say is important and all. But think about
    if you added some great pictures or video clips to give your posts more, “pop”!
    Your content is excellent but with pics and videos, this website could definitely be one of the most
    beneficial in its niche. Fantastic blog!

    https://w8.datamacau.buzz/

  18. The 10 Scariest Things About Auto Accident top rated Car Accident lawyers (http://153.126.169.73)

  19. Hey there just wanted to give you a quick heads up. The words in your article
    seem to be running off the screen in Opera. I’m not sure if this is a
    format issue or something to do with internet browser compatibility but I figured I’d post to let you know.

    The design and style look great though! Hope you get the problem solved soon. Many thanks

  20. Leonie表示:

    Patio Outdoor Gas Heater Tools To Ease Your Daily Lifethe One Patio Outdoor Gas Heater Trick Every Individual Should Know patio outdoor gas heater (Leonie)

  21. I pay a visit day-to-day some web sites and information sites to read posts,
    but this blog provides feature based content.

    https://w2.rajaprediksi.cfd/

  22. Derekfar表示:

    en cok kazand?ran slot oyunlar?: slot oyunlar? puf noktalar? – slot oyunlar?

  23. LarryCoell表示:

    casino siteleri win Deneme Bonusu Veren Siteler Casino Siteleri

  24. Diplomi_slkn表示:

    дипломы аттестаты дипломы аттестаты .

  25. Derekfar表示:

    ultrabet: ultrabet guncel – ultrabet

  26. Best Electric Wheelchair For Travel: The Good, The Bad, And The Ugly lightweight
    electric Wheelchair; https://kingranks.com/author/judohair2-149287/,

發佈留言

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