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,155,500 Responses

  1. Good day! This post could not be written any better!
    Reading this post reminds me of my old room mate!

    He always kept chatting about this. I will forward this article to
    him. Pretty sure he will have a good read.

    Many thanks for sharing!

  2. Nicely put. Thanks!

  3. maxman表示:

    Saved as a favorite, I like your web site!

  4. I am truly glad to glance at this web site posts which carries plenty of useful facts, thanks for providing these
    data.

  5. The 10 Most Scariest Things About Good Online Shopping
    Sites Uk good online shopping sites uk

  6. Anthonynix表示:

    MOBILE GAMES & APP DEVELOPMENT
    https://www.fanstudio.co.uk/

  7. Guide To Double Glazed Window Near Me: The Intermediate Guide Towards Double Glazed Window
    Near Me double glazed Window near me

  8. r 7表示:

    R7 Casino гарантирует высокий уровень защиты персональных данных и финансовых транзакций, используя современные методы шифрования.

  9. bokep terbaru表示:

    I’m truly enjoying the design and layout of your blog.
    It’s a very easy on the eyes which makes it much more pleasant for
    me to come here and visit more often. Did you hire out a developer to create your theme?

    Great work!

  10. palsy表示:

    9 Things Your Parents Teach You About Cerebral Palsy Lawsuit palsy

  11. A Step-By-Step Guide To Selecting The Right Personal Injury Case Personal Injury Law Firm

  12. What Best Coffee Machine Experts Want You To Know?
    Best Pod Coffee Machine Uk

  13. Danieldob表示:

    Всем привет! Подскажите, где найтиполезные статьи о недвижимости? Сейчас читаю https://tent44.ru

  14. You’ll Be Unable To Guess Automatic Folding Mobility Scooter Near Me’s Secrets automatic folding mobility scooter near me

  15. 15 Things To Give Those Who Are The Slot Rankings Lover In Your Life best
    slots (maps.google.com.sa)

  16. Danieldob表示:

    Всем привет! Может кто знает, где найтиразные статьи о недвижимости? Пока нашел https://tent44.ru

  17. Kermit表示:

    Wisdom On L Shaped Double Beds From The Age Of Five t shaped bunk beds (Kermit)

  18. Slot offers表示:

    What’s Holding Back The Best Slot Payouts Industry?
    Slot offers

  19. Scatter slots表示:

    15 Things You Don’t Know About Progressive Jackpot Slots Scatter slots

  20. Danieldob表示:

    Приветствую. Может кто знает, где найтиразные блоги о недвижимости? Пока нашел https://tent44.ru

  21. You’ll Be Unable To Guess Amazon Online Grocery Shopping
    Uk’s Tricks Amazon online grocery shopping uk (http://www.archeus.ro)

  22. asbestos case表示:

    An asbestos lawyer can assist victims file a suit against the company that exposed them to asbestos case.
    A lawsuit can help victims recover compensation for medical expenses in addition to lost wages and other damages.

  23. The Most Hilarious Complaints We’ve Seen About New
    Upvc Door Replacing Lock In Upvc Door (Jazzforum.Com.Pl)

  24. Shelli表示:

    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.

  25. 15 Pinterest Boards That Are The Best Of All Time About Couch With Chaise Leather couch with chaise

發佈留言

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