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,479,483 Responses

  1. AnthonyWIZ表示:

    4AqH6px8UNDTUn2w8LUY

  2. Профессиональный сервисный центр по ремонту сотовых телефонов в Москве.
    Мы предлагаем: починка ноутбуков
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  3. Pressez表示:

    Excellent article! News releases are key for shaping media messages and sharing crucial
    news. They help build connections between companies and press.
    Writing impactful press releases means being direct, aligned
    with the interests of relevant media outlets. In the modern media landscape,
    press releases further act a vital role in web-based
    PR. They merely target mainstream news outlets but additionally increase engagement and strengthen a company’s digital presence.

    Adding images, such as photos, can make press
    releases even interesting and accessible. Adapting to the evolving
    media sphere while keeping core principles can greatly amplify a
    press release’s effect. How do you feel on leveraging multimedia in press releases?

    Have a look at my web blog: Pressez

  4. Princess Deal表示:

    The Reason Why Retro Fridge Freezer Will Be Everyone’s Desire In 2023 Slim Retro Fridge Freezer – https://Nativ.Media:443/Wiki/Index.Php?Wavemist8

  5. Art Molineux表示:

    The 10 Most Terrifying Things About Pellet Stoves Inserts Pellet Stoves inserts

  6. Key For Bmw Tools To Ease Your Everyday Lifethe Only Key For Bmw Trick Every Individual Should Know key for bmw [August]

  7. What Do You Know About Bio-Fireplace? Bio fireplace – Minecraftcommand.science,

  8. Deanne Bowler表示:

    10 Failing Answers To Common Pragmatic Free Slot Buff Questions Do You Know Which Ones?프라그마틱 무료게임

  9. AaronIdelt表示:

    7 simple secrets to eating the Mediterranean way
    kra9 cc
    What if “diet” wasn’t a dirty word?

    During Suzy Karadsheh’s childhood in Port Said, Egypt, diet culture was nonexistent.

    “My parents emphasized joy at the table, rather than anything else,” Karadsheh said. “I grew up with Mediterranean lifestyle principles that celebrate eating with the seasons, eating mostly whole foods and above all else, sharing.”

    But when Karadsheh moved to the United States at age 16, she witnessed people doing detoxes or restricting certain food groups or ingredients. Surrounded by that narrative and an abundance of new foods in her college dining hall, she says she “gained the freshman 31 instead of the freshman 15.” When she returned home to Egypt that summer, “I eased back into eating the Mediterranean food that I grew up with. During the span of about two months, I shed all of that weight without thinking I was ever on a diet.”
    To help invite joy back to the table for others — and to keep her family’s culinary heritage alive for her two daughters (now 14 and 22) — Atlanta-based Karadsheh launched The Mediterranean Dish food blog 10 years ago. Quickly, her table started getting filled with more than just her friends and family.

    “I started receiving emails from folks whose doctors had prescribed the Mediterranean diet and were seeking approachable recipes,” Karadsheh said. The plant-based eating lifestyle, often rated the world’s best diet, can reduce the risk for diabetes, high cholesterol, dementia, memory loss and depression, according to research. What’s more, the meal plan has been linked to stronger bones, a healthier heart and longer life.

    Preparing meals the Mediterranean way, according to Karadsheh, can help you “eat well and live joyfully. To us, ‘diet’ doesn’t mean a list of ‘eat this’ and ‘don’t eat that.’” Instead of omission, Karadsheh focuses on abundance, asking herself, “what can I add to my life through this way of living? More whole foods, vegetables, grains, legumes? Naturally, when you add these good-for-you ingredients, you eat less of what’s not as health-promoting,” she told CNN.

  10. buketik39.ru表示:

    Don’t Believe These “Trends” Concerning Adhd Symptoms For
    Women adult male adhd Symptoms (buketik39.ru)

  11. 5 Tools That Everyone Involved In Test For ADHD In Adults Industry
    Should Be Making Use Of online test For adhd for adults (https://iam-psychiatry92738.ka-blogs.com/)

  12. Профессиональный сервисный центр по ремонту сотовых телефонов в Москве.
    Мы предлагаем: вызвать мастера по ремонту ноутбуков
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  13. 10 Quick Tips About Car Key Remote Repair Near Me remote control car key repairs

  14. BrandonJer表示:

    cheapest online pharmacy india pharmacy website india Online medicine home delivery

  15. Wilbert Mayo表示:

    The Most Sour Advice We’ve Ever Received On Nissan Juke Key Fob Nissan key fob Replacement near me

  16. Gregorypurne表示:

    medications for ed https://drugs24.pro/# best male enhancement pills

  17. BrandonJer表示:

    best online pharmacies in mexico mexican border pharmacies shipping to usa mexican online pharmacies prescription drugs

  18. Unquestionable Evidence That You Need Asbestos Mesothelioma Lawyers mesothelioma Lawsuit

  19. Hugo Lemaster表示:

    10 Books To Read On Glass Repairing Seals

  20. Viola Gage表示:

    The 9 Things Your Parents Teach You About Childrens Bunk Bed childrens Bunk Bed

  21. I blog often and I truly appreciate your content. The article has
    really peaked my interest. I am going to bookmark your blog
    and keep checking for new information about once per week.
    I subscribed to your Feed as well.

  22. What Refrigerators Samsung Could Be Your Next Big Obsession Refrigerator Samsung Models

  23. AgustinBougs表示:

    https://drugs24.pro/# the best ed drug
    mail order pharmacy india

  24. AgustinBougs表示:

    http://indianpharmdelivery.com/# pharmacy website india
    pharmacy website india

  25. Terrellnut表示:

    Game boosting service https://gamerspecials.com/

  26. How To Get More Results From Your 3 Wheeler Pushchairs 3 Wheel Pushchair sale

  27. Barb Bagot表示:

    How To Outsmart Your Boss On Treehouse Bed treehouse style Bed

  28. Iris Brydon表示:

    5 Killer Quora Answers On 3 Wheeler Stroller 3 wheeler Stroller (Stroud-sandberg.Thoughtlanes.net)

  29. Gregorypurne表示:

    ed natural treatment https://drugs24.pro/# comfortis without vet prescription

發佈留言

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