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,479,834 Responses

  1. It�s hard to come by educated folks for this topic, however, you seem like you know what you�re talking about! Thanks

    Here is my site – http://Himeuta.org/member.php?1540119-Eldarzqf

  2. Brilliant Reply to Web Publication Remark

    Fantastic piece! I’m absolutely reveling in the topic on this forum.
    Have you ever contemplated pertaining to acquiring as part of electronic betting betting?
    Evolution Gaming is a brilliant website including a vast range of top-notch engaging croupier offerings.

    The venture is so captivating and real, it feels akin to you’re squarely there in the genuine gaming.

    Should you’re drawn on the topic of experiencing the platform too, I’d
    be thrilled to offer my exclusive referral website address.
    The Evolution offers a excellent signup deal for prospective recent bettors.
    It undoubtedly undisputedly helpful examining more if you’re looking for a changed internet
    casino activities experience.

    Thanks as well with regards to this web publication content.
    Maintain up the undertakings!

    Also visit my blog :: gambling user experience

  3. Eau d'argent表示:

    I don’t know whether it’s just me or if everyone else encountering issues with your site.
    It appears as though some of the written text in your content are running off the screen. Can somebody else
    please comment and let me know if this is happening to them as well?
    This could be a issue with my web browser because I’ve had this happen before.
    Appreciate it

  4. Blakesmema表示:

    кухни под заказ — Закажите кухню, идеально подходящую вашему интерьеру.

  5. Inez Terry表示:

    After reading this, I’m convinced that every organization, big or small TreeStone Security Services

  6. Late Night Fun 오피커뮤니티 – http://sekken-life.com,

  7. 13 Things About Realisticsexdolls You May Never Have Known Realistic adult Doll

  8. I believe what you wrote made a ton of sense.
    But, what about this? what if you composed a catchier title?
    I ain’t saying your content isn’t good., however what if you added a title that grabbed a person’s attention? I mean JS 依照元素出現數量排序 – 馬老師 雲端研究室 is a little vanilla.
    You could glance at Yahoo’s front page and see how they write news titles to grab viewers to open the links.
    You might try adding a video or a picture or two to grab readers interested
    about everything’ve written. Just my opinion,
    it might bring your website a little bit more interesting.

    Here is my blog – realtor in Meridian Ms

  9. I’m gone to say to my little brother, that he should also go to see this webpage on regular basis to obtain updated from
    newest gossip.

  10. Hey There. I found your weblog using msn. This is a very well written article. I will be sure to bookmark it and return to read extra of your useful information. Thank you for the post. I will definitely return.

  11. Nikefut表示:

    darknet links bitcoin dark web deep web drug links

  12. Таким образом, автосервис на Ржевке – это надежный помощник для вашего автомобиля. Если вам нужен профессиональный ремонт или техническое обслуживание, не стесняйтесь обращаться сюда. Здесь вас ждут опытные специалисты, удобное расположение и доступные цены. Ваш автомобиль заслуживает только лучшего!
    https://5-boks.clients.site

  13. Do you have any video of that? I’d like to find out more details.

    my web site: best real estate agent in tucson az

  14. GordonCef表示:

    Полный электронный архив Полный электронный архив Республики Алтай. Со всеми приказами, распоряжениями, письмами и прочим.

  15. The Reason You Shouldn’t Think About Making Improvements To Your Mens
    Masturbation Toys best Male masturbatora

  16. HK Pools表示:

    When I originally left a comment I appear to have clicked the -Notify me when new comments are added- checkbox and now each
    time a comment is added I get four emails with the exact same
    comment. Is there an easy method you are able to remove me from
    that service? Thanks!

    https://w3.hkpols.help/

  17. Hi there, yeah this paragraph is truly pleasant and I have learned lot of
    things from it about blogging. thanks.

發佈留言

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