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,371,421 Responses

  1. BernardMop表示:

    stromectol ivermectin tablets inverfast.com ivermectin 24 mg

  2. Appreciate the comprehensive advice. For more, visit roofers near me

  3. Nikefut表示:

    dark market 2024 darkmarket 2024 https://darknetmarketstore.com/ – deep web sites

  4. This piece of writing is truly a nice one it helps new net users, who are wishing in favor of blogging.

  5. Veridex Prime表示:

    I’m amazed, I must say. Rarely do I come across a blog that’s both
    educative and interesting, and let me tell you, you’ve hit the
    nail on the head. The issue is something too few men and women are speaking
    intelligently about. I am very happy that I stumbled across this in my hunt for something concerning
    this.

  6. LamarFob表示:

    Access medicine facts. Get medicine info.
    buy proscar online
    Find pill info. Complete medicine overview.

  7. How do you guys feel about using recycled materials in new construction like reclaimed wood paired with modern metals? Visit my site for unique combinations: commercial roofing company

  8. acim表示:

    Cool blog! Is your theme custom made or did you download it from somewhere?
    A theme like yours with a few simple tweeks would
    really make my blog shine. Please let me know where you
    got your theme. Appreciate it

  9. DougLIG表示:

    одним словом БЕЛКА
    Son oyun yenil?m?l?r v? basl?q ucun oxuyun mostbet city times weekly edition for regular updates and specials!

  10. Gregory Gill表示:

    Thanks for sharing these tips! I’ve been looking into SEO for my law firm and found great resources at seo for lagal firm

  11. Link building表示:

    This paragraph will assist the internet people
    for building up new webpage or even a blog from start to end.

  12. Ian Garrett表示:

    Content marketing can be a game changer for lawyers. I recommend exploring strategies at seo for legal firms

  13. I have read so many content about the blogger lovers except this piece of writing is really a nice post, keep it up.

  14. Узнай все о удаление полипа в матке стоимость москваудаление полипа эндометрия москва

  15. JacobLoody表示:

    http://goldcoon.ru/ – Удобный сервис для выбора кухни вашей мечты.

  16. Fantastic tips on maintaining a roof! Regular inspections can save you a lot of money in the long run roofing company

  17. Loved your point about personal branding as a lawyer local seo for lawyers

  18. slot gacor表示:

    Hey I know this is off topic but I was wondering if
    you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates.
    I’ve been looking for a plug-in like this for quite some
    time and was hoping maybe you would have some experience with something like this.
    Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.

  19. A well-rounded perspective addressing intersections between personal branding cultivating authentic narratives establishing credibility ultimately enhancing visibility distinguishing professionals amidst competitive l seo company for lawyers

  20. Della Freeman表示:

    Great points made here about the role of content in legal SEO! For further reading, visit attorney seo companies

  21. If you’re looking for something eco-friendly, metal roofs are recyclable! Find out more benefits at metal roofers

  22. Great job highlighting the importance of analytics in measuring SEO success—I learned some new tools from your recommendations as well as from seo marketing for law firms

  23. Maud Abbott表示:

    Excellent discussion about flat roofs vs pitched roofs—the pros tile roofers

發佈留言

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