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,243,935 Responses

  1. I all the time emailed this weblog post page to all my friends, since if like to read it next my contacts
    will too.

  2. BrandenSlomy表示:

    generic amoxicillin: amoxil – order amoxicillin online

  3. StevenNub表示:

    dapoxetine price: dapoxetine price – cheap priligy

  4. When someone writes an piece of writing he/she retains the image
    of a user in his/her brain that how a user can be aware of it.
    Therefore that’s why this paragraph is perfect. Thanks!

  5. Pilitte.Com表示:

    You’ll Never Guess This Where Is The Best Place To Buy Bunk Beds’s Tricks Bunk Bed (Pilitte.Com)

  6. Aproveite as mais abrangentes interpretacoes.
    Porque e que sonho com o kvass?

    [url=https://oldias.com/discussion/topic/discover-where-to-find-after-hours-alcohol-in-toronto-2/?part=333#postid-105493]Com que e que um elefante sonha?[/url] [url=https://www.bapter.ro/default-post-type/comment-page-180025/#comment-182533]Porque e que sonho com o kvass?[/url] [url=http://infosheet.org/node/3875?page=825#comment-58301]Sonho de um gato adormecido[/url] [url=https://alrawdalighting.com/2023/06/13/hello-world/#comment-18136]O que e que eu sonho em mudar de emprego?[/url] [url=https://saveyorkgardens.co.uk/forum/topic/the-full-case-against-winstanley-york-rd-scheme-social-cleansing-and-contempt-for-local-residents-2/?part=48694#postid-684820]Sonha com um cao que morde o seu braco? Doeu e sangrou? Interpretacao de um sonho de acordo com diferentes livros de sonho[/url] 7c49793

  7. If you are going for most excellent contents like I do,
    only pay a quick visit this site everyday since it offers feature contents, thanks

  8. BrandenSlomy表示:

    order clomid without a prescription: cost of clomid without a prescription – how to get clomid without prescription

  9. Bradleygoath表示:

    can i order cheap clomid prices clomid where can i get clomid prices

  10. Markdob表示:

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

  11. Markdob表示:

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

  12. Тут можно преобрести сейф под ружье купить оружейные шкафы москва

  13. Bradleygoath表示:

    how to buy clomid online clomid cost cheap clomid without dr prescription

  14. Dereketerm表示:

    how to get generic clomid pills: generic clomid – where buy generic clomid pill

  15. Тут можно преобрести сейфы под оружие оружейный сейф на заказ москва

  16. BrandenSlomy表示:

    generic amoxicillin over the counter: amoxicillin online without prescription – buy cheap amoxicillin online

  17. Узнай все о лапароскопия варикоцеле варикоцеле 2 степени

  18. Markdob表示:

    Приветствую. Может кто знает, где почитатьразные статьи о недвижимости? Сейчас читаю – https://artpronn.ru

  19. Bradleygoath表示:

    Priligy tablets dapoxetine online priligy

  20. Markdob表示:

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

  21. Узнай все о двустороннее варикоцеле варикоцеле слева у мужчин

  22. BrandenSlomy表示:

    get cheap clomid price: clomid – can you buy cheap clomid now

發佈留言

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