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,452,795 Responses

  1. If some one desires expert view concerning blogging and site-building after that i advise him/her to pay a visit this blog, Keep up the fastidious job.

  2. This is a topic that’s near to my heart… Thank you!
    Exactly where are your contact details though?

  3. Rickyalies表示:

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

  4. Brandonnot表示:

    Mexican Easy Pharm: mexican border pharmacies shipping to usa – Mexican Easy Pharm

  5. CurtisBam表示:

    Online pharmacy: Best Indian pharmacy – IndianCertPharm

  6. Boostaro表示:

    You actually make it seem really easy together with your presentation but I find this topic to
    be actually something which I feel I’d by no means understand.
    It sort of feels too complicated and very huge for
    me. I’m having a look forward in your next put up, I’ll try to get the hang of it!

  7. My pets love lounging in our new patio enclosure as much as we do—it’s their favorite spot too! patio screen enclosure options

  8. The 3 Greatest Moments In Robot Vacuum Black Friday History best robot hoover

  9. Glenn Goodman表示:

    This was nicely structured. Discover more at استخدام نیروی نمایشگاهی

  10. Iyannaobesk表示:

    все уроки покера лесного
    уроки покера лесного скачать

  11. Telegra.Ph表示:

    Watch Out: How Asbestos Mesothelioma Is Gaining Ground
    And What To Do About It Mesothelioma Lawsuit [Telegra.Ph]

  12. CurtisBam表示:

    Mexican Easy Pharm: Mexican Easy Pharm – Mexican Easy Pharm

  13. Carrolleruck表示:

    https://mexicaneasypharm.com/# mexican rx online
    canada drugs

  14. Do you think pressure washing can help prepare a house for sale? I’ll definitely check out Wilson Windows for more information! Pressure Washing Burlington

  15. CurtisBam表示:

    indian pharmacy: Indian pharmacy international shipping – Online pharmacy

  16. CurtisBam表示:

    Online pharmacy: Indian Cert Pharm – Indian Cert Pharm

  17. budal表示:

    Some Good Clubs Which Worth Visiting budal

  18. CurtisBam表示:

    mexican pharmaceuticals online: buying from online mexican pharmacy – Mexican Easy Pharm

  19. Brandonnot表示:

    Online medicine: top 10 online pharmacy in india – Indian Cert Pharm

  20. CurtisBam表示:

    Mexican Easy Pharm: mexico drug stores pharmacies – Mexican Easy Pharm

  21. Sophia Meyer表示:

    Thanks for the helpful article. More like this at رنگ ضد حریق

  22. Hello there, I discovered your site by means of Google while
    searching for a similar subject, your website got here up, it
    seems great. I’ve bookmarked it in my google bookmarks.

    Hello there, just changed into aware of your weblog
    through Google, and located that it is really informative.
    I am going to be careful for brussels. I’ll be grateful
    for those who proceed this in future. Lots
    of other folks might be benefited from your writing. Cheers!

  23. Eden表示:

    I am now not certain the place you’re getting your info,
    but good topic. I must spend a while finding out much more or understanding more.
    Thanks for wonderful information I used to be searching
    for this info for my mission.

    Besides, LMCHING, a top-tier online system for luxury appeal, is redefining exactly how skin care
    lovers discover and purchase the globe’s most acclaimed brands.

    With a focus on easy-to-use innovation and customer-centric functions, LMCHING makes
    it easy for clients to locate and acquire premium skincare products from top sector brands.

    LMCHING is giving top priority to shipping to important worldwide markets, such
    as the United States, UK, Australia, Canada, France, Singapore, Switzerland, UAE, Germany, and New Zealand.

    Through its ingenious strategy, LMCHING takes on the difficulties that typically come with accessing high-end
    skin care.

    With its smooth interface and durable logistics, the system ensures that appeal enthusiasts throughout continents can delight in items that
    integrate sophisticated science and exceptional high-end.

    This development is particularly considerable for consumers seeking La Prairie and La Mer– 2 brand names that represent the pinnacle of skincare quality.

    With its commitment to mobile scientific research, La Prairie has redefined the
    skincare industry with its extravagant and powerful formulas.

    La Prairie’s collections, including the Skin Caviar Collection and the
    exclusive Platinum Rare line, deal transformative outcomes, making them a relied on choice for those seeking remarkable
    anti-aging therapies.

    LMCHING makes these complex, science-driven formulas obtainable
    effortlessly, making sure beauty fanatics in key areas can check out and appreciate the very best of Swiss technology.

    Likewise, La Mer stays a worldwide icon of restoration and indulgence.

    La Mer’s popular Crème de la Mer and the progressive Genaissance de la Mer line
    show the brand’s combination of marine-based components with modern technology.

    The Treatment Lotion, together with other items, has actually redefined standards for hydration and revitalization in skin care.

    LMCHING delivers these extraordinary items with both effectiveness
    and dependability to consumers in expanding worldwide markets.

    With a concentrate on shipping to nations like the United States, UK, and
    Australia, LMCHING meets the increasing need for deluxe
    skin care in these markets.

    Consumers in Canada, France, and Germany, understood
    for their historical appreciation of premium charm, can currently access LMCHING’s carefully curated option and efficient worldwide shipping.

    Skin care lovers in Switzerland, Singapore, New Zealand, and the UAE
    now have accessibility to these extremely sought after brand names, getting rid of the difficulty of limited regional supply.

    What collections LMCHING apart is its commitment to supplying not simply items, but a raised shopping experience.

    LMCHING gets rid of obstacles that normally block accessibility to luxury charm by using
    innovation to streamline product exploration and distribution.

    Every item offered on the system goes through rigorous quality control to guarantee authenticity, using consumers self-confidence in their acquisitions.

    LMCHING’s selection to extend shipping to 10 worldwide markets
    highlights its dedication to meeting the requirements of a wide and broadening clientele.

    LMCHING makes sure that consumers in Asia-Pacific markets like Singapore and Australia can access cutting-edge La Prairie and La Mer items with trusted
    shipment.

    In markets like the UAE, where luxury appeal is very pertained to, LMCHING guarantees very easy accessibility to both distinguished and
    emerging skin care brands.

    From La Prairie’s cutting edge Skin Caviar Luxe Cream to La Mer’s exceptional Crème de la Mer, LMCHING makes these products
    both accessible and delightful to explore.

    LMCHING’s careful growth shows its dedication to combining complicated technology with
    simplicity and convenience, solidifying its duty as a relied on accessibility point
    for high-end skin care.

    With this global initiative, LMCHING is establishing a brand-new standard in the on-line elegance industry.

    By mixing technological innovation with client understanding, LMCHING makes it easy to access renowned skincare brand names such as La Prairie and La Mer.

    With a solid devotion to high quality, ease of
    access, and client satisfaction, LMCHING is redefining the concept of luxury charm on a global range.

    LMCHING is a famous number in the high-end
    beauty industry, perfectly linking cutting-edge skincare solutions with a worldwide audience in a classy manner.

    Here is my web page; top-rated La Prairie and La Mer products
    (Eden)

  24. CurtisBam表示:

    mexican online pharmacies prescription drugs: mexican online pharmacies prescription drugs – mexican mail order pharmacies

  25. CurtisBam表示:

    reputable indian pharmacies: Online pharmacy – Indian Cert Pharm

發佈留言

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