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,466,950 Responses

  1. вывод из запоя дешево ростов-на-дону вывод из запоя дешево ростов-на-дону .

  2. BOKEP TERBARU表示:

    Very nice post. I just stumbled upon your weblog and
    wished to say that I’ve really enjoyed surfing around your blog posts.
    In any case I will be subscribing to your rss feed and I hope you write again soon!

  3. Manie表示:

    This Is The One Window Hinges Trick Every Person Should Be Able To how to measure window hinges – Manie

  4. вызвать капельницу от запоя на дому вызвать капельницу от запоя на дому .

  5. I was suggested this blog by my cousin. I’m not sure whether this post is written by
    him as no one else know such detailed about my problem.
    You’re wonderful! Thanks!

  6. Chet表示:

    Thanks for sharing your info. I truly appreciate your efforts and I am waiting for your next write ups thanks once again.

  7. Leanna表示:

    10 Things That Your Competitors Help You Learn About Fridge UK cheap fridge uk –
    Leanna

  8. 성동구쪽에 돈 많은 손님 많아요~ 팁 많이 받으세요~ 성동구 노래방알바로 연락 주세요

  9. Wallacefex表示:

    sweet bonanza kazanma saatleri: sweet bonanza slot – sweet bonanza yorumlar

  10. Online Casino表示:

    Wow that was unusual. I just wrote an really long comment but after I clicked submit my comment didn’t appear.

    Grrrr… well I’m not writing all that over again. Anyway, just wanted to say wonderful blog!

  11. JasonUnsoG表示:

    https://casinositeleri25.com/# casino en iyi siteler

  12. Medication information. Short-Term Effects.
    can i purchase neurontin pills
    All information about pills. Get now.

  13. Can I simply say what a relief to find someone
    that actually understands what they are discussing
    on the internet. You certainly know how to bring a problem to light and make it important.
    A lot more people really need to look at this and understand this side
    of your story. I was surprised you are not more popular
    because you surely possess the gift.

  14. Johnnie表示:

    Hey There. I found your blog using msn. This is an extremely well written article.
    I’ll make sure to bookmark it and return to read
    more of your useful info. Thanks for the post. I’ll
    definitely return.

  15. JasonUnsoG表示:

    https://casinositeleri25.com/# Casino Siteleri

  16. JasonUnsoG表示:

    https://denemebonusuverensiteler25.com/# deneme bonusu veren siteler

  17. вывод из запоя на дому ростов круглосуточно вывод из запоя на дому ростов круглосуточно .

  18. Wallacefex表示:

    canl? casino siteleri: Casino Siteleri – deneme bonusu veren casino siteleri

  19. BradleyEdino表示:

    sweet bonanza yorumlar sweet bonanza yorumlar sweet bonanza yorumlar

  20. 100 먹튀검증 먹튀사이트 목록 확인 커뮤니티 먹튀모음 토토사이트 메이저사이트 스포츠 미니게임 파워볼 꽁머니사이트 모든 사이트 먹튀검증을 시행하고 있으며, 가장 빠른 먹튀검증사이트입니다 먹튀모음은 먹튀에서 안전한 공식 보증업체를 추천해드리며, 부당한 일을 당하지 않게 체계적인 시스템으로 운영하고
    있습니다

  21. вывод из запоя в стационаре ростов-на-дону [url=www.vyvod-iz-zapoya-rostov229.ru/]www.vyvod-iz-zapoya-rostov229.ru/[/url] .

  22. Aisha表示:

    It is the best time to make some plans for the future and it is time to be happy.
    I’ve read this submit and if I could I want
    to suggest you few interesting issues or suggestions.
    Perhaps you could write subsequent articles referring to this article.
    I desire to read even more issues about it!

  23. Michaelcib表示:

    Portugal has long been a country known for producing exceptional talent in the world of sports. With a rich history in football, many athletes from this nation have achieved international fame through their incredible skills and accomplishments http://users.atw.hu/sajprobaoldalam/modules.php?name=Journal&file=display&jid=51097

發佈留言

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