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

  1. BrandenSlomy表示:

    cheap priligy: max pharm – priligy maxpharm

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

  3. DarrenUnjuh表示:

    https://iverfast.com/# stromectol ivermectin

  4. Markdob表示:

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

  5. Markdob表示:

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

  6. Nikefut表示:

    darknet drug links tor dark web https://mydarknetmarketlinks.com/

  7. DarrenUnjuh表示:

    http://plavixclo.com/# buy plavix

  8. BrandenSlomy表示:

    where can i get generic clomid without prescription: clomid rex pharm – can i buy generic clomid without rx

  9. First off I would like to say great blog! I had a quick question in which I’d like to ask if you don’t mind.

    I was curious to find out how you center yourself and clear
    your mind prior to writing. I’ve had a difficult time clearing my thoughts in getting my thoughts out.

    I do take pleasure in writing but it just seems like the
    first 10 to 15 minutes are lost just trying to figure out how to begin. Any recommendations or hints?
    Thank you!

  10. RopenaBitApp表示:

    It is appropriate time to make some plans for the future and it’s time to be happy.
    I have read this post and if I could I want to suggest
    you some interesting things or advice. Perhaps you could write next articles referring to this article.
    I wish to read more things about it!

  11. Scottputty表示:

    This read was worth every second give it a try https://ourfamilylync.com/read-blog/26733

  12. casino joy表示:

    Если вы хотите быстро покрутить слоты,
    сыграть несколько партий в
    блэкджек или принять участие в живом казино, Joycasino предлагает все,
    что вам нужно.

  13. BernardMop表示:

    lisinopril1st cheap lisinopril lisinopril1st

  14. instead of problem-solving,ダッチワイフthe discussion turned into a battle of My way.

  15. Hey! I know this is kinda off topic however I’d figured I’d ask.
    Would you be interested in trading links or maybe guest authoring a blog article or
    vice-versa? My website addresses a lot of
    the same topics 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!
    Wonderful blog by the way!

  16. BrandenSlomy表示:

    cheap priligy: priligy – Priligy tablets

  17. Your pointers on boosting website rate are actually spot on! As an SEO expert, I understand how crucial this is actually. Explore more at seo expert

發佈留言

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