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,368,009 Responses

  1. Nikefut表示:

    deep web search dark internet https://darknetmarketstore.com/ – darknet site

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

  3. JacobLoody表示:

    https://goldcoon.ru/ – Откройте для себя широкий ассортимент кухонь на заказ.

  4. Hello! I’ve been following your website for
    some time now and finally got the bravery to go ahead and give you a shout out from
    Humble Texas! Just wanted to mention keep up the good work!

  5. Markdob表示:

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

  6. cam girls表示:

    Hi! Do you know if they make any plugins to protect against hackers?
    I’m kinda paranoid about losing everything I’ve worked hard on.
    Any recommendations?

  7. link wajik777表示:

    Howdy! I know this is kinda off topic however I’d figured I’d ask.
    Would you be interested in exchanging links or maybe guest authoring a blog article or vice-versa?
    My website discusses a lot of the same subjects as yours and I believe we could
    greatly benefit from each other. If you’re interested feel free
    to shoot me an e-mail. I look forward to hearing from you!
    Awesome blog by the way!

  8. Markdob表示:

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

  9. Узнай все о операция по удалению полипа шейки маткигистероскопия удаление полипа

  10. cancertoto表示:

    cancer toto,cancertoto,cancer toto login login daftar
    cancer toto,cancertoto,cancer toto login login daftar cancer toto,
    cancertoto,cancer toto login login daftar cancer toto,cancertoto,cancer toto login login daftar cancer toto,cancertoto,
    cancer toto login login daftar

  11. Very good post. I absolutely appreciate this website.
    Keep writing!

  12. RopenaBit App表示:

    Wow, this piece of writing is good, my younger sister is analyzing these kinds of things, therefore I
    am going to convey her.

  13. Markdob表示:

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

  14. Medication prescribing information. Long-Term Effects.
    can you get erythromycin without rx
    Actual information about medicine. Read here.

  15. Markdob表示:

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

  16. Sazrshh表示:

    Вопросы и ответы: можно ли быстро купить диплом старого образца?

    odesit.com/user.php?id.14271

  17. Good day! I know this is kinda off topic however I’d figured I’d ask.
    Would you be interested in exchanging links or maybe guest authoring a blog article or
    vice-versa? My site covers a lot of the same subjects as yours and I think we could
    greatly benefit from each other. If you are interested feel
    free to send me an email. I look forward to
    hearing from you! Great blog by the way!

  18. DerekWab表示:

    http://huskytaxi.ru/ – ваше решение для уникального дизайна кухни.

  19. test hack表示:

    Thanks for finally writing about > JS 依照元素出現數量排序 – 馬老師 雲端研究室 < Loved it!

  20. Descubra o mundo misterioso do desconhecido.
    Porque e que sonho com uma cruz partida?

    [url=https://www.razboinici.ro/forum/index.php?action=vthread&forum=1&topic=9&page=1630#msg346542]Sonho de um gato adormecido[/url] [url=https://streetlite.com/get-involved/ministries/#comment-298820]Olhar num espelho num sonho[/url] [url=https://demos.appthemes.com/hirebee/projects/t-shirt-design/comment-page-13/#comment-354]Porque e que sonho com uma cruz partida?[/url] [url=http://gluckadvisory.com/hello-world/#comment-47201]Sonha com um cao que morde o seu braco? Doeu e sangrou? Interpretacao de um sonho de acordo com diferentes livros de sonho[/url] [url=https://jcbschool.com/hello-world/#comment-196519]Porque e que sonho com uma cruz partida?[/url] c49d717

  21. Hi there, You’ve done an excellent job. I will certainly digg it
    and personally suggest to my friends. I’m sure they will be benefited from this site.

  22. WengToto表示:

    I reallу lіke what yoս guys tend to Ьe up toⲟ.
    This type of clever w᧐rk and reporting! Keeep up the wonderful works guys I’νe included you guys to my personal blogroll.

    Review my web-site :: WengToto

  23. I’m extremely inspired with your writing abilities as neatly as with the structure for your weblog.
    Is that this a paid theme or did you modify it your self?
    Anyway stay up the nice high quality writing, it is uncommon to look a nice weblog like this one these days..

  24. baywin giriş表示:

    Greate post. Keep writing such kind of information on your blog.
    Im really impressed by your blog.
    Hello there, You have done an incredible job. I will certainly digg
    it and personally recommend to my friends. I’m confident they will be benefited
    from this site.

  25. Safety Fence表示:

    Good day! I could have sworn I’ve been to your blog before but after going through many of the posts
    I realized it’s new to me. Anyhow, I’m definitely happy
    I stumbled upon it and I’ll be book-marking it and checking back
    regularly!

  26. Attractive component of content. I just stumbled upon your weblog and in accession capital to
    claim that I get in fact enjoyed account your weblog posts.

    Anyway I’ll be subscribing on your augment and even I fulfillment you get right of entry to persistently rapidly.

  27. Sazrjks表示:

    Как быстро получить диплом магистра? Легальные способы

    tricityfriends.com/read-blog/3765

  28. Nikefut表示:

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

  29. Sazrdpc表示:

    Официальная покупка диплома вуза с сокращенной программой в Москве

    datasphere.ru/club/user/15/blog/

  30. Купить дапоксетин без рецептов в Санкт-Петербурге с доставкой https://spb-generic.ru/poxet большой выбор
    препаратов для мужчин в наличии по выгодным ценам

發佈留言

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