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,169,257 Responses

  1. Ferne表示:

    The People Nearest To Window Companies High Wycombe Share Some Big Secrets double
    glazing for sash windows high wycombe – Ferne,

  2. Arlen Nizo表示:

    20 Tools That Will Make You More Effective At Car Boot Scooters Arlen Nizo

  3. Hello there! Do you know if they make any
    plugins to safeguard against hackers? I’m kinda paranoid about losing everything I’ve worked
    hard on. Any tips?

  4. It’s hard to come by well-informed people about this topic,
    however, you seem like you know what you’re talking about!
    Thanks

  5. 5 Laws That Can Help The Land Rover Discovery 3 Key Fob
    Replacement Industry freelander 2 key fob replacement

  6. The 10 Most Terrifying Things About Cerebral Palsy
    Law cerebral palsy

  7. dob表示:

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

  8. You’ll Never Guess This Window Replacement Near
    Me’s Tricks window replacement near me

  9. Online Shop表示:

    Five Killer Quora Answers To Online Shop Online Shop

  10. Что нужно знать перед походом к стоматологу, рекомендуем.
    Современные технологии в стоматологии, качественный уход за зубами.
    Основные причины зубной боли, ознакомиться.
    Самые популярные заблуждения о зубах, эффективные советы стоматолога.
    Секреты крепких и белоснежных зубов, прочитать.
    Лечение зубов без боли: реальность или миф?, качественные методики стоматологии.
    Как избежать неприятного запаха изо рта, советуем.
    стоматологія клініка https://klinikasuchasnoistomatologii.vn.ua/ .

  11. jerealas表示:

    10 Wrong Answers To Common Double Glazing Door Repairs Near Me Questions Do
    You Know The Correct Answers? jerealas

  12. You’ll Be Unable To Guess Online Shop Designer
    Suits’s Tricks Online shop designer suits

  13. Online Shopping Uk Electronics Tools To Help You Manage Your Everyday Lifethe Only
    Online Shopping Uk Electronics Trick That Every Person Should
    Be Able To Online Shopping uk Electronics

  14. Good day! This post could not be written any better! Reading this post reminds me of my good old room mate!
    He always kept chatting about this. I will forward this write-up to him.
    Pretty sure he will have a good read. Thanks for sharing!

  15. tgslot表示:

    I am regular visitor, how are you everybody? This paragraph posted at this
    web site is in fact pleasant.

  16. BomesJoype表示:

    Lorem Ipsum has been the industry’s standard dummy text https://soniamarco.it/ngqotq of type and scrambled it to make a type specimen book.

  17. Heya i am for the first time here. I found this board and I find It really useful & it helped me out much.
    I hope to give something back and aid others like you helped me.

  18. website表示:

    If some one wants to be updated with most recent technologies then he must be
    visit this site and be up to date every day.

  19. I really like what you guys tend to be up too. Such clever work and reporting!
    Keep up the great works guys I’ve you guys to my blogroll.

  20. The 10 Most Scariest Things About Online Retailers
    Uk Stats Online retailers uk Stats

發佈留言

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