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,478,512 Responses

  1. DarrenUnjuh表示:

    http://plavixclo.com/# Cost of Plavix without insurance

  2. Markdob表示:

    Всем привет! Подскажите, где найтиполезные статьи о недвижимости? Сейчас читаю – https://tpkv94.ru

  3. Nikefut表示:

    darkmarket 2024 how to access dark web blackweb official website

  4. Thank you for any other excellent article. The place else may anybody get that type
    of info in such an ideal manner of writing? I’ve a presentation next week, and I am on the search for such information.

  5. JE: If there may be any good to return out of all the injuries we’ve had, might it perhaps be the opportunity that has all of the sudden offered itself to the likes of Josh O’Keefe?

  6. AlbertDuM表示:

    buy Lisinopril 1st: lisinopril 10mg online – zestril 10 mg cost

  7. BrandenSlomy表示:

    order prednisone online canada: Prednisone Without Prescription – prednisone buy without prescription

  8. just kill pro表示:

    Info nicely applied..

    Feel free to visit my blog post; https://justkill.ru

  9. Regards! A lot of information.

  10. BernardMop表示:

    Abortion pills online buy cytotec online cytotec abortion pill

  11. Nikefut表示:

    dark markets 2024 dark website dark net

  12. Hi it’s me, I am also visiting this web site on a regular
    basis, this web page is really nice and the users are genuinely sharing pleasant thoughts.

  13. ### Mantel Clocks for Fireplace: Timeless Elegance for Your Home

    The fireplace often serves as the heart of a home, creating a warm and inviting ambiance. To further enhance its charm, a carefully chosen mantel clock can act as a centerpiece, combining functionality with aesthetic appeal. Mantel clocks for fireplaces have long been symbols of sophistication, and their timeless designs continue to captivate homeowners.

    #### The History of Mantel Clocks
    Mantel clocks, also known as shelf clocks, originated in the 18th century as compact timepieces designed to sit atop a fireplace mantel. These clocks became popular in European homes for their elegance and practicality. Crafted from materials like wood, brass, and porcelain, they often featured intricate details, showcasing the craftsmanship of their era.

    #### Why Choose a Mantel Clock for Your Fireplace?
    1. **Aesthetic Appeal**: Mantel clocks come in a variety of designs, from traditional to modern, making them a versatile decorative piece for any home style.
    2. **Functional Elegance**: Beyond telling time, these clocks add a touch of sophistication to your living space.
    3. **Conversation Starter**: A unique or antique mantel clock can spark interest and become a cherished focal point.
    4. **Balance and Proportion**: Placing a clock on your fireplace mantel adds balance to the overall decor, tying the room together.

    #### Types of Mantel Clocks
    1. **Traditional Mantel Clocks**: Featuring ornate carvings and classic Roman numerals, these are ideal for vintage or classic interiors.
    2. **Modern Mantel Clocks**: With sleek lines and minimalist designs, they suit contemporary homes.
    3. **Chiming Mantel Clocks**: These clocks produce melodic chimes, adding an auditory charm to their visual appeal.
    4. **Antique Mantel Clocks**: Perfect for collectors, these clocks are rich in history and craftsmanship.

    #### Choosing the Perfect Mantel Clock
    When selecting a mantel clock for your fireplace, consider the following:
    – **Size**: Ensure the clock fits proportionally on your mantel without overwhelming the space.
    – **Material**: Match the clock’s material to other elements in the room, such as wood, metal, or ceramic.
    – **Mechanism**: Choose between mechanical, quartz, or battery-operated clocks based on your preferences.
    – **Style**: Select a design that complements your room’s decor, whether it’s rustic, modern, or traditional.

    #### Care and Maintenance of Mantel Clocks
    To keep your mantel clock in top condition:
    – **Regular Cleaning**: Dust the clock regularly using a soft, dry cloth.
    – **Winding**: If you own a mechanical clock, wind it according to the manufacturer’s instructions.
    – **Professional Servicing**: For antique clocks, seek professional maintenance to preserve their intricate mechanisms.
    – **Placement**: Avoid placing the clock in direct sunlight or near extreme heat to prevent damage.

    #### Where to Find Mantel Clocks
    Mantel clocks are available in:
    – **Antique Stores**: For vintage and unique pieces with historical value.
    – **Home Decor Shops**: Offering a wide range of modern and traditional styles.
    – **Online Marketplaces**: Providing convenience and variety at competitive prices.

    #### Conclusion
    A mantel clock is more than just a timepiece; it’s a statement of style and elegance. Whether you prefer a modern design or an antique treasure, these clocks can elevate the look of your fireplace and your home. With the right choice, a mantel clock can become a cherished heirloom, adding timeless beauty and charm to your living space.

    https://hikvisiondb.webcam/wiki/User:KrystynaAlbrecht

  14. TerryUtine表示:

    На данный момент антигравийная пленка считается материалом, который отлично защищает кузов авто от различных повреждений. Так, она поможет избежать царапин, потертостей, а также предохраняет машину во время небольших ДТП, и в результате на поверхности авто не появляется ржавчина https://www.drive2.ru/o/b/720303/

  15. Medication information sheet. Long-Term Effects.
    how to buy tadacip without insurance
    All trends of medicines. Read information now.

  16. Howdy! I could have sworn I’ve been to this site before but after
    checking through some of the post I realized it’s new to
    me. Anyways, I’m definitely happy I found it and I’ll be
    book-marking and checking back frequently!

  17. 출장表示:

    Social Gathering 출장

  18. Flora Simon表示:

    This was very enlightening. For more, visit Oakland Criminal Defense Lawyer

  19. BrandenSlomy表示:

    buy priligy max pharm: dapoxetine price – buy priligy max pharm

  20. AlbertDuM表示:

    buy cytotec pills online cheap: buy cytotec online – Abortion pills online

  21. How To Get Money By Playing Games – Creating A Lot Income In The Casino 에볼루션 유출

  22. At this time I am going to do my breakfast, when having my breakfast coming over again to read additional news.

  23. If you desire to increase your know-how simply keep
    visiting this web page and be updated with the most up-to-date information posted
    here.

  24. Maisie表示:

    Private Party 오피커뮤니티 (Maisie)

  25. I read this article fully regarding the difference of most recent
    and preceding technologies, it’s amazing article.

  26. Hi! This is kind of off topic but I need some guidance from an established blog.

    Is it very hard to set up your own blog? I’m not very techincal but I can figure things out pretty quick.

    I’m thinking about making my own but I’m not sure where
    to begin. Do you have any ideas or suggestions?

    With thanks

    Also visit my blog post – โค้ด เครดิตฟรี

發佈留言

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