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

  1. Markdob表示:

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

  2. rajabandot表示:

    This paragraph presents clear idea in favor of the new users of blogging, that really how to do
    blogging.

    My homepage: rajabandot

  3. xem sex表示:

    Phim sex địt nhau của Nhật Bản, Việt Nam,
    và các châu á, châu âu. daycuroabando.vn địt nhau mạnh bảo nhất, xem phim sex tải nhanh xem sướng
    nhất hội.

  4. Markdob表示:

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

  5. Astounding Blog Thoughts
    Astounding, what a compelling blog ! I sincerely relished perusing your
    perspectives on this subject .
    As someone who has been observing your online presence for
    a duration , I need to communicate that this
    is one of your finest eloquently crafted and enthralling content thus far .

    The way you integrated various angles and scholarly results was
    sincerely impressive . I discovered myself as I perused because your points solely seemed to advance
    astonishingly naturally .

    Review my web-site: bitcoin online casino

  6. Triangle Billiards & Bar Stools
    1471 Nisson ᎡԀ, Tustin,
    CᎪ 92780, United Ѕtates
    +17147715380
    Tri Billiards Repair Technique

  7. BrandenSlomy表示:

    buy priligy: priligy – max pharm

  8. porno sex表示:

    Way cool! Some very valid points! I appreciate you writing this article
    plus the rest of the site is also really good.

  9. Markdob表示:

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

  10. Nikefut表示:

    deep web markets deep web sites https://darknetmarketstore.com/ – deep web drug url

  11. Iyannaobesk表示:

    игровой аппарат fortune mouse gratis
    fortune mouse gratis на деньги

  12. StevenNub表示:

    where can i get cheap clomid price: can i order generic clomid price – generic clomid without a prescription

  13. StevenNub表示:

    priligy: priligy max pharm – buy dapoxetine online

  14. bokep indo表示:

    You really make it seem so easy with your presentation but I find this matter to be really something that I think I would never understand.
    It seems too complicated and extremely broad for me. I’m looking forward for your next post,
    I’ll try to get the hang of it!

  15. Markdob表示:

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

  16. Equinunk表示:

    I do not even know how I ended up here, but I thought this post was good.
    I do not know who you are but definitely you’re going to
    a famous blogger if you are not already 😉 Cheers!

  17. Markdob表示:

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

  18. Dear fans of football matches
    Like me, you probably bet on football matches and probably haven’t become lotto millionaires or at least successful
    players yet.
    If this is the case, then my proposal is extremely suitable for you!

    It comes down to this: I offer to teach you the art
    of football betting to multiply your chances of success
    with your bets.
    Betting is the art of making the right choices and
    therefore it is critical to be able to avoid the pitfalls in it.

    The system I offer you requires that you possibly maintain your databases from which
    you draw information for your final betting choice using the linear regression made
    according to my algorithm.
    This is a highly accurate system that guarantees
    incredible Swarm on a monthly and yearly basis!

    If you are busy and don’t care about maintaining your databases, which
    is really time-consuming and partly difficult to apply in our busy life, I offer you
    a second option, namely to use ready-made results from sites
    like “int.soccerway.com “, which you will then double-check: once the so-called “fair odds ratios” will be determined, and then you will do a second control
    analysis using my kind of linear regression.
    This is a fairly quick way to determine your favorite matches to bet on, but it does
    not have the determination of the advance reliability of the
    predictions as in option #1, but still has its familiarity of over 65% as an average result
    for the various football championships.
    Thank you for your attention
    Doctor Dimitar Kehaiov

    Bulgaria

  19. This information is priceless. How can I find out more?

  20. ngewe表示:

    I believe that is among the most significant info for me.
    And i am glad studying your article. However should commentary on some general things, The web site style is
    wonderful, the articles is truly nice : D. Just right job, cheers

  21. Howdy, I think your site could be having web browser compatibility problems.
    Whenever I look at your web site in Safari, it looks fine however, when opening in Internet Explorer,
    it has some overlapping issues. I simply wanted to provide you
    with a quick heads up! Apart from that, excellent blog!

發佈留言

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