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,245,276 Responses

  1. If some one desires to be updated with most up-to-date technologies after that he must be pay a visit this web page and be
    up to date daily.

  2. xxx表示:

    Hi there, i read your blog from time to time and i own a similar one
    and i was just wondering if you get a lot of spam responses?

    If so how do you prevent it, any plugin or anything you can recommend?
    I get so much lately it’s driving me crazy so
    any help is very much appreciated.

  3. JacobLoody表示:

    https://www.mtucizone.ru/ — Наши проекты, советы и вдохновение для вашей кухни.

  4. What’s up to all, it’s in fact a fastidious for me to go to see
    this site, it contains valuable Information.

  5. RafaelAdowl表示:

    Когда я увидел этот мир, ощущение было таким, будто я нашёл что-то особенное. Здесь каждая игра — это не просто азарт, а история, которую ты ощущаешь с каждым движением.

    Дизайн удобен, словно невидимый проводник направляет тебя от игры к игре. Транзакции, будь то депозиты или вывод средств, проходят быстро, как поток воды, и это удивляет. А поддержка всегда готова подхватить, как друг, который никогда не подведёт.

    Для меня Казино селектор стал миром, где игра и вдохновение сплетаются. Здесь каждая минута — это часть картины, которую хочется писать снова и снова.

  6. BrandenSlomy表示:

    buying prednisone on line: cheap prednisone – buying prednisone on line

  7. Lunch Medis表示:

    Pretty great post. I simply stumbled upon your blog and
    wished to mention that I’ve truly loved surfing around
    your weblog posts. After all I’ll be subscribing on your rss feed and I’m hoping you
    write again very soon!

  8. Nikefut表示:

    darkweb marketplace darknet links https://darknetmarketstore.com/ – dark web search engine

  9. I have read some good stuff here. Definitely value bookmarking for revisiting.
    I wonder how much attempt you put to make the sort of excellent informative site.

  10. BrandenSlomy表示:

    cheap priligy: dapoxetine online – buy dapoxetine online

  11. Profix Bot表示:

    Hi everybody, here every one is sharing such experience,
    thus it’s pleasant to read this blog, and I used to pay a
    quick visit this blog every day.

  12. Hello to all, how is the whole thing, I think every one is getting more from
    this site, and your views are pleasant in support of new users.

  13. Dereketerm表示:

    priligy: buy dapoxetine online – dapoxetine online

  14. Yes! Finally someone writes about auto repair.

  15. بهمن表示:

    I’ve learn a few excellent stuff here. Certainly price bookmarking for revisiting.
    I wonder how much attempt you set to create any such magnificent informative website.

  16. gay sex表示:

    Hey! Someone in my Myspace group shared this website with us so I came to look it over. I’m definitely loving the information. I’m book-marking and will be tweeting this to my followers! Great blog and fantastic design.

  17. Blakesmema表示:

    north-web.ru — Ваши идеи — наша реализация. Узнайте больше о наших кухнях.

  18. LeonardKnism表示:

    кухни на заказ – Осуществляем проекты кухонь любой сложности с учетом ваших пожеланий.

  19. StevenNub表示:

    amoxicillin 500mg capsule cost: amoxil – amoxicillin 500mg price canada

  20. Nikefut表示:

    darknet links darknet marketplace https://darknetmarketstore.com/ – darkmarket 2024

  21. Kamu hanya memerlukan URL dari video yang ingin diunduh dan klik tombol download.

  22. BrandenSlomy表示:

    dapoxetine price: max pharm – priligy maxpharm

  23. WengToto表示:

    When ѕome ⲟne searches fоr һіѕ vital thіng, thᥙs he/shе
    desires to Ƅe available tһat in detail, therefore that thing is
    maintained ονеr here.

    my blog; WengToto

發佈留言

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