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,423,309 Responses

  1. What Experts Say You Should Learn Accident Car Lawyer

  2. LeroyBak表示:

    over the counter ed remedies affordable medication canada ed drugs

  3. Aaronrem表示:

    Собственное производство пластиковых окон – выгодные цены без посредников, подробности здесь https://www.codecademy.com/profiles/Thomas835

  4. BrettVup表示:

    Link Building Services
    ]link building services
    Hey there, future SEO rockstar! Ready to skyrocket your business to new heights? Let’s dive into the exciting world of link building services that can seriously amp up your online presence. Whether you’re just starting out or looking to boost your existing strategy, we’ve got the lowdown on the coolest methods out there—think crowd marketing, guest posting, PBNs, and more!
    Why Link Building is Your New Best Friend
    First things first: why should you care about link building? Well, in the digital universe, backlinks are like high-fives from other websites telling search engines, “Hey, this site is pretty cool!” The more quality high-fives you get, the more popular you become in the eyes of Google and friends. And you know what that means—higher rankings, more traffic, and a whole lot of new customers knocking on your virtual door.
    Guest Posting: Share Your Voice with the World
    Imagine getting to share your ideas on someone else’s platform and gaining their audience’s trust. That’s guest posting in a nutshell! You create killer content for other websites in your niche, and in return, you get a sweet backlink to your site. Why It’s Cool: You tap into new audiences, build your brand’s credibility, and boost your SEO. Pro Tip: Make sure your content is top-notch and adds real value. No one likes fluff!
    Crowd Marketing: Join the Conversation
    Crowd marketing is all about jumping into online communities—forums, social media groups, you name it—and sharing your wisdom. It’s not about shameless plugs; it’s about being genuinely helpful. Why It’s Cool: You build relationships, establish yourself as an expert, and earn organic backlinks. Pro Tip: Be authentic. People can spot a fake from a mile away.

  5. 5 Qualities That People Are Looking For In Every
    Upvc Window Repairs upvcwindows (http://www.instapaper.com)

  6. duct split表示:

    mohajer-co.com
    Good day! Do you use Twitter? I’d like to follow you if that would be okay.
    I’m definitely enjoying your blog and look forward to new updates.

  7. DevonPhack表示:

    http://indianpharm24.pro/# buy prescription drugs from india
    prescription drugs

  8. 20 Resources To Make You Better At L Shaped Sleeper Sofa leather sleeper Couch

  9. LeroyBak表示:

    medicine in mexico pharmacies mexican pharmacy mexican pharmaceuticals online

  10. Jorgeagopy表示:

    best online pharmacies in mexico: mexican pharm 24 – purple pharmacy mexico price list

  11. LeroyBak表示:

    muse for ed low cost prescription pharmacy online

  12. AndrewPhice表示:

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

  13. bokep表示:

    Somebody necessarily assist to make significantly articles I would state.

    That is the very first time I frequented your web page and
    to this point? I amazed with the analysis you made
    to create this particular submit amazing. Wonderful process!

  14. DevonPhack表示:

    https://indianpharm24.pro/# Online medicine home delivery
    treating ed

  15. tấm compact表示:

    hi!,I really like your writing so so much! proportion we keep up a correspondence extra
    approximately your article on AOL? I require an expert on this
    area to solve my problem. Maybe that is you!

    Having a look ahead to look you.

  16. The Best Advice You’ll Ever Receive On Asbestos Attorney mesothelioma Attorney

  17. BrandonSaisy表示:

    canadian drugs online: cheap drugs – how to treat ed

  18. LeroyBak表示:

    indianpharmacy com Pharmacies in India that ship to USA cheapest online pharmacy india

  19. 15 Of The Most Popular Pinterest Boards Of All Time About Door Fitters Maidstone
    upvc window Repair maidstone

  20. slot gacor表示:

    This is my first time pay a visit at here and i
    am genuinely impressed to read everthing at alone place.

  21. Check Out: How Best Sex Machine Is Taking Over And What Can We Do About It Buy A sex Machine

  22. Wendell表示:

    9 Things Your Parents Teach You About Key Cutting
    Car key cutting car [Wendell]

發佈留言

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