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,611,827 Responses

  1. Greetings from Idaho! I’m bored to tears at work so I decided to check
    out your blog on my iphone during lunch break. I enjoy the info you provide here and can’t wait to take a look when I get home.
    I’m surprised at how fast your blog loaded on my mobile
    .. I’m not even using WIFI, just 3G .. Anyways, fantastic site!

  2. ผมเลย ล่าสุด อ่านบล็อกนี้ และรู้สึกใจเต้นแรง
    มาก! ข่าวสาร ที่น่าสนใจพร้อมกับ
    รายละเอียดในอัน ครบถ้วน ทำให้ผมได้รับประสบการณ์ ใหม่ๆ
    มากมาย ผมชอบวิธีการ ที่คุณทบทวน ประเด็นต่างๆ อย่างละเอียด และชี้ให้เห็น แนวคิดที่น่าสนใจ ผมเห็นด้วยกับ หลายจุดที่คุณกล่าวถึง และมองว่าเป็นเรื่องซึ่งสำคัญและควรได้รับการพิจารณา อย่างลึกซึ้ง
    นอกจากนี้ ผมยังปลื้ม ความแปลกใหม่ ในการนำเสนอ เนื้อหา การใช้ภาษา ที่ใช้เข้าใจง่าย และการออกแบบ ที่น่าสนใจ เพราะ อ่านแล้วรู้สึกสดชื่น เป็นบล็อกที่ดีเยี่ยม และน่าติดตามเป็นพิเศษ
    ขอแสดงความชื่นชม ที่แบ่งปันข้อมูล
    และความคิดเห็น ที่น่าสนใจ
    ผมรอแวะมาติดตาม ที่จะอ่านบทความใหม่ๆ ของคุณในภายหน้า และหวังว่าจะได้มีช่องทาง แลกเปลี่ยน ความรู้สึก
    กับคุณด้วย

    Here is my site – เว็บ หวยออนไลน์

  3. Medicine information for patients. Cautions.
    is augmentin same as amoxicillin
    All information about drugs. Get information now.

  4. 10 Things You Learned In Kindergarden To Help You Get Started With French Door Fridge Ice
    Maker french door fridge counter Depth – mosegaard-albrektsen-3.blogbright.net

  5. click here表示:

    Superb, what a blog it is! This blog gives valuable
    data to us, keep it up.

  6. See What Situstoto Slot Tricks The Celebs Are Using Situstoto Slot

  7. This is a topic that’s close to my heart… Take care! Where are your contact details though?

  8. Latisha表示:

    The Top Maxi Cosi Pebble Car Seat Gurus Are Doing Three Things maxi cosi familyfix 2 compatible seats (Latisha)

  9. Jeromecog表示:

    Ремонт Мерседес в Москве — Клубный сервис
    мерседес бенц сервис
    Ремонт и обслуживание Mercedes: Надежность и качество от профессионалов
    Автомобили Mercedes-Benz давно зарекомендовали себя как эталон надежности, комфорта и престижа. Однако, как и любой автомобиль, даже самые надежные модели нуждаются в своевременном обслуживании и ремонте. Для поддержания вашего Mercedes в отличном состоянии необходимо выбирать специализированный сервис, который предлагает профессиональный ремонт и обслуживание.
    Ремонт и обслуживание автомобилей Mercedes — это сложный процесс, требующий профессионального подхода и знаний. Выбирая специализированный сервис, вы гарантируете своему автомобилю надежную и качественную работу, а себе — уверенность и безопасность на дороге. Не экономьте на обслуживании, ведь своевременный ремонт поможет избежать больших расходов в будущем и сохранить ваш Mercedes в идеальном состоянии на долгие годы.

  10. slot表示:

    I’ve been surfing online more than 3 hours nowadays, but I never found any
    fascinating article like yours. It’s pretty value sufficient for me.
    Personally, if all website owners and bloggers made good content as you did, the
    net will be a lot more helpful than ever before.

  11. Guide To Replacement Window Hinges: The Intermediate Guide On Replacement
    Window Hinges Replacement window hinges

  12. bradsindyEks表示:

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

  13. slot gacor表示:

    Heya i am for the first time here. I came across this board and I find It truly useful & it helped me out much.

    I hope to give something back and help others
    like you aided me.

  14. Many companies involved in the production of Asbestos (Milne-Gallegos-2.Technetbloggers.De) knew of its dangers but
    failed to warn their employees or their customers. These companies that were
    negligent should be accountable for their conduct.

  15. 10 Quick Tips On Non Asbestos Causes Of Mesothelioma mesothelioma Lawyer

  16. Austin表示:

    3 Wheel Rollator Lightweight Explained In Fewer Than 140 Characters stable rollator, Austin,

  17. RileyBok表示:

    Viagra * Cialis * Levitra

    All the products you are looking seeking are currently convenient as far as something 1+1.

    4 more tablets of identical of the following services: Viagra * Cialis * Levitra

    https://pxman.net

  18. 9 Lessons Your Parents Taught You About Small Sofa
    L Shape Small sofa L shape

  19. Your means of telling the whole thing in this article is genuinely pleasant,
    all can simply understand it, Thanks a lot https://www.provenexpert.com/fr-fr/pub025/

  20. Your means of telling all in this article is in fact good,
    all can without difficulty understand it,
    Thanks a lot https://www.provenexpert.com/en-us/pub025/

  21. 11 Methods To Completely Defeat Your Wall Fireplace
    Electric wall hanging fireplaces

  22. slot gacor表示:

    Wow, this article is good, my younger sister is analyzing these things, thus I
    am going to convey her.

  23. Sazroyq表示:

    Пошаговая инструкция по официальной покупке диплома о высшем образовании

    moneyschoolinc.mn.co/posts/69998942

  24. 20 Trailblazers Setting The Standard In Upvc Windows Repair Upvc window repairs Near Me

  25. A片表示:

    Howdy this is kinda of off topic but I was wanting to
    know if blogs use WYSIWYG editors or if you have to manually code
    with HTML. I’m starting a blog soon but have no coding skills so I wanted to get guidance
    from someone with experience. Any help would be enormously appreciated!

    Feel free to surf to my page: A片

發佈留言

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