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,197,199 Responses

  1. One Of The Most Innovative Things Happening With Link Builder Software Backlink Building Software

  2. Erotikanzeigen

    Nice weblog here! Additionally your site lots up very fast!
    What web host are you using? Can I am getting your associate hyperlink
    for your host? I want my site loaded up as fast as yours lol

  3. Medicines prescribing information. What side effects?
    get risperdal without dr prescription
    Actual trends of drugs. Get now.

  4. I do not even know how I ended up here, but I thought this post was great.
    I do not know who you are but certainly you are going to
    a famous blogger if you aren’t already 😉 Cheers!

  5. A Relevant Rant About Bunk Beds For Children http://www.eddafay.top

  6. 4nettie.net表示:

    Also visit my blog post: where to find sex near me; 4nettie.net,

  7. Medicine information sheet. What side effects can this medication cause?
    can i buy cheap neurontin without rx
    All information about medicament. Read information now.

  8. 1win表示:

    Приложение имеет современный дизайн в довольно элегантной темно-синей цветовой
    гамме..

    Take a look at my webpage; 1win

  9. Drug information for patients. Brand names.
    where can i get cheap ipratropium without a prescription
    Actual what you want to know about drug. Read information here.

  10. testimonios表示:

    **Unlocking the Potential of OmniHack: Revolutionizing the World of Hacking**

    In the ever-evolving landscape of cybersecurity and technology, the term “OmniHack” has emerged as a pivotal concept that promises to redefine the boundaries of ethical hacking. OmniHack represents a paradigm shift in how cybersecurity professionals approach vulnerability testing, penetration testing, and ethical hacking in general. This article delves into what OmniHack entails, its significance, and its implications for the future of cybersecurity.

    **What is OmniHack?**

    OmniHack can be best described as a comprehensive approach to ethical hacking that integrates various methodologies, tools, and techniques. Unlike traditional hacking practices that may focus on specific vulnerabilities or systems, OmniHack takes a holistic view. It encompasses a wide range of targets, including web applications, networks, mobile devices, and cloud infrastructures. The goal is not just to identify weaknesses but to provide a thorough assessment of an organization’s entire security posture.

    **Key Features of OmniHack**

    1. **Cross-Platform Compatibility:** OmniHack is designed to work across different platforms and environments. This versatility allows cybersecurity professionals to assess and secure complex infrastructures comprehensively.

    2. **Automation and AI Integration:** Leveraging automation and artificial intelligence, OmniHack streamlines the process of vulnerability detection and analysis. This not only accelerates the testing phase but also enhances accuracy in identifying potential threats.

    3. **Scalability:** Whether for small businesses or large enterprises, OmniHack offers scalable solutions tailored to the specific needs and complexities of each organization. This scalability ensures that cybersecurity efforts remain effective and efficient regardless of size.

    4. **Continuous Monitoring and Assessment:** Beyond one-time assessments, OmniHack promotes continuous monitoring and assessment. This proactive approach helps organizations stay ahead of emerging threats and vulnerabilities in real-time.

    **The Significance of OmniHack**

    OmniHack represents more than just a technological advancement; it embodies a shift in mindset towards proactive cybersecurity. By adopting OmniHack methodologies, organizations can:

    – **Enhance Security Posture:** By identifying and addressing vulnerabilities proactively, organizations can significantly reduce the risk of cyberattacks and data breaches.

    – **Meet Compliance Requirements:** Many regulatory frameworks require organizations to conduct regular security assessments. OmniHack facilitates compliance by providing robust testing and reporting capabilities.

    – **Boost Efficiency:** Automation and AI-driven processes streamline security assessments, allowing cybersecurity teams to focus on strategic initiatives rather than routine tasks.

    – **Foster Innovation:** OmniHack encourages innovation in cybersecurity practices by integrating cutting-edge technologies and methodologies.

    **The Future of OmniHack**

    As technology continues to advance, so too will the capabilities of OmniHack. Future iterations may include enhanced AI capabilities, advanced threat modeling, and integration with emerging technologies such as blockchain and IoT security. Moreover, as cybersecurity threats become more sophisticated, OmniHack will play a crucial role in safeguarding digital assets and maintaining trust in the digital economy.

    In conclusion, OmniHack represents a pivotal advancement in the field of ethical hacking and cybersecurity. By embracing its holistic and proactive approach, organizations can fortify their defenses against evolving cyber threats while fostering a culture of continuous improvement and innovation in cybersecurity practices. As we look towards the future, OmniHack is poised to lead the charge in securing the digital landscape for years to come.
    omnihack

    my web blog; https://lopermedia.com/

  11. Pills information. Brand names.
    where can i get cheap lyrica without a prescription
    Everything information about meds. Get information here.

  12. Wһat’s up to every body, it’s my fiгst pay а visit of this blog; this weblog
    consists օf amazing and reaⅼly excellent іnformation for
    readers.

    Feel frede tto visit mү site: Model Escorts in Islamabad

  13. It’s actually a cool and useful piece of info.
    I am glad that you shared this helpful info with us. Please keep us up to date like this.
    Thank you for sharing.

  14. I?ll immediately grab your rss as I can not find your email subscription link or e-newsletter service. Do you have any? Please let me know so that I could subscribe. Thanks.

  15. Excellent blog you have got here.. It’s difficult to find excellent writing like yours
    these days. I really appreciate people like you! Take
    care!!

  16. BomesJoype表示:

    Lorem Ipsum has been the industry’s standard dummy text https://creosell.pl/raoyhic of type and scrambled it to make a type specimen book.

  17. Effective, Efficient Keyword Research 백링크 확인

  18. Bank Rate Loan Calculator: Free And Uncomplicated 전세자금 대출

  19. สวัสดีทุกคน! ผมเพิ่งจะได้ทดลองเล่น เว็บสล็อต askmebet และจำเป็นต้องบอกว่าชอบใจมากครับ กราฟิกงดงามมากมาย แล้วก็อินเตอร์เฟซใช้งานง่ายอย่างยิ่งมีเกมให้เลือกเล่นจำนวนมากและก็โบนัสก็น่าดึงดูด ผู้ใดกันที่กำลังมองหาเว็บไซต์สล็อตดีๆเสนอแนะให้ลองเล่น
    askmebet เครดิตฟรี เลยครับผม รับรองว่าคุณจะไม่ผิดหวังแน่นอน

  20. Excellent way of explaining, and nice post to take facts concerning
    my presentation topic, which i am going to present in university.

  21. $1,000 Fast Payday ” Loan ” Loan Can Ease Financial Emergencies 월세 보증금 대출

  22. Medication information. Effects of Drug Abuse.
    where to get lasix without dr prescription
    Actual news about medicine. Get information here.

  23. Hi, I do believe your website may be having internet browser compatibility problems.
    When I take a look at your web site in Safari, it looks fine
    however when opening in IE, it’s got some overlapping issues.
    I merely wanted to provide you with a quick heads up!
    Aside from that, great website!

  24. free code BC.Game in Brazil

  25. Medicines information for patients. Cautions.
    can i get cheap erythromycin
    Best information about medicine. Read now.

  26. discuss表示:

    Ϝirst ⲟff I ᴡould ⅼike to say terrific blog! І hadd a quick question tһat I’d like
    to ask if you don’t mind. Ӏ was interestеd to know how you
    center yoursеⅼf and cleаr your mind prior to writing.
    I have had trouble clearing my thօughts inn getting my tһoughts out.
    Itruly do tаke pleasure in writing һowever
    it just seеms liқe the first 10to 15 minutes are lost simply
    јust trying to figure out howw too Ьegin. Any
    ideas ⲟr tips? Tһank you!

    Feel free to visit mү page – discuss

  27. uk88表示:

    Superb, what a web site it is! This web site gives useful information to us, keep it up.

  28. This post is worth everyone’s attention. How can I find out
    more?

發佈留言

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