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,713 Responses

  1. That is a really good tip particularly to those new
    to the blogosphere. Short but very precise information…
    Thanks for sharing this one. A must read post!

  2. Link exchange is nothing else except it is simply placing the other person’s website link on your page at appropriate place and other person will also do similar for you.

  3. bisma777表示:

    Hey! Quick question that’s completely off topic. Do you know
    how to make your site mobile friendly? My site looks weird when viewing from my
    iphone4. I’m trying to find a template or
    plugin that might be able to resolve this problem.

    If you have any suggestions, please share. Appreciate it!

  4. Five Great European Travel Destinations 광주키스방

  5. Very nice article, just what I needed.

  6. Post writing is also a fun, if you be acquainted with afterward you can write or else it is complicated to write.

  7. BradleyEdino表示:

    deneme bonusu veren siteler yat?r?ms?z deneme bonusu veren siteler deneme bonusu veren yeni siteler

  8. JacobLoody表示:

    https://pravoslavieug.ru/ — Перейдите на официальный сайт pravoslavieug для создания кухни мечты.

  9. Sqirk表示:

    A private Instagram viewer is a tool or minister to meant to permit users to view private Instagram accounts without
    needing to follow the account or get hail from the
    account owner. Typically, these listeners affirmation to bypass privacy settings
    and have enough money right of entry to posts, stories, and supplementary content that would otherwise be restricted to
    followers. while some people may use these tools out of curiosity or for social media analysis,
    its important to note that using such services raises supreme
    ethical and real concerns. Most of these spectators play a role in a gray area,
    often violating Instagram’s terms of advance and potentially putting users’ privacy and data at risk.
    In addition, many of these tools require users to unquestionable surveys or
    offer personal information, which can lead to scams, phishing attempts, or malware infections.
    Instagram has strict policies next to unauthorized entry to
    accounts and may take on legitimate law adjoining both users and
    services lively in breaching privacy. otherwise of relying on private Instagram viewers, it’s advisable to love users’ privacy settings and follow accounts in a valid manner.
    If someone has made their account private, its generally a sign that they hope to limit
    access to their content, and these boundaries should be respected.

    Here is my page: Sqirk

  10. Roulette Strategies Tip To Play Safe And Win The Game On Casinos 에볼루션 라이트닝

  11. Miquel表示:

    My partner and I absolutely love your blog and find many of
    your post’s to be what precisely I’m looking for. can you offer guest writers to write content available for you?
    I wouldn’t mind writing a post or elaborating on most
    of the subjects you write in relation to here. Again, awesome site!

  12. вывод из запоя цены на дому ростов вывод из запоя цены на дому ростов .

  13. Agnes Fields表示:

    Thanks for the informative content. More at Advosy Roofing and Construction

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

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

  16. Looking For Inspiration? Look Up SEO Marketing Agency seo Agency Birmingham

  17. It is appropriate time to make some plans for the longer term and
    it is time to be happy. I have read this put up and if I could I wish to counsel you some fascinating things or tips.
    Perhaps you can write subsequent articles referring to this article.
    I wish to learn even more things about it!

  18. This was very beneficial. For more, visit los angeles moving and storage companies

  19. Adele Lynch表示:

    Are there any first-time homebuyer programs offered by Tacoma mortgage lenders? I found some useful info at Tacoma Home Loan

  20. BradleyEdino表示:

    canl? casino siteleri casino bahis siteleri Canl? Casino Siteleri

  21. The study was supported financially by Apoteket AB, including support to the e. KelseysWoods.com, KelseysWoods, KWBIGTIME, WTMCA. A hurl of fundamental ones of landon are juice viagra apotek online not one. Support online, Currency: USD, EUR GBP CAD AUD CHF SEK NOK DKK. apotek, English translation, bab.la Swedish-English dictionary. With Guaranteed lowest prices.There are several factors that affect the length of. Dreams from the Woods is now available online, It is the full movie that Little. Pharmacy with a team of experienced and Licensed Pharmacists, Online Viagra. Great value, discreet and convenient online Pharmacy.We offer everything you. Viagra Apotek Online, Eliminate Refractory Period. https://sverigegenerisk.com/ledercort/ Bestalla Ledercort Kosta

  22. капельница от запоя ростов на дону капельница от запоя ростов на дону .

  23. вывод из запоя на дому в ростове на дону вывод из запоя на дому в ростове на дону .

發佈留言

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