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,480,570 Responses

  1. Salvatore表示:

    15 Reasons You Must Love Pragmatic Site 프라그마틱 무료체험 (Salvatore)

  2. I am sure this paragraph has touched all the internet people, its really really fastidious paragraph on building up new web site.

  3. Roy Jobson表示:

    The 10 Most Terrifying Things About Situs Toto Login Situs toto login

  4. Guide To Car Key Spares: The Intermediate
    Guide To Car Key Spares car key Spares

  5. 15 Of The Top Fire Media Wall Bloggers You Should Follow inset media wall fire

  6. BrandonJer表示:

    п»їbest mexican online pharmacies mexican rx online mexican online pharmacies prescription drugs

  7. ebet gambling表示:

    Remarkable Blog Post
    Incredible, what an perceptive and contemplative
    content! I came across myself affirming as I scanned
    through your examination of this vital matter.

    Your points were thoroughly investigated and
    communicated in a lucid, convincing manner. I notably appreciated how you were able
    to extract the essential subtleties and intricacies at
    operation , excepting oversimplifying or disregarding the
    challenges .
    This write-up has presented me a lot to reflect on .

    You’ve definitively widened my understanding and
    altered my mindset in certain significant ways .

    Thank you for investing the effort to share
    your expertise on this matter . Articles like this are extremely a invaluable input to the discussion .
    I anticipate experiencing what other insightful data you have in
    supply.

    my web site; ebet gambling

  8. big tits表示:

    Having read this I believed it was rather informative. I appreciate you taking the time and effort to put this content together.

    I once again find myself personally spending way too much time both reading and posting comments.

    But so what, it was still worthwhile!

  9. 10 Pinterest Accounts To Follow About Pragmatic Game 프라그마틱 무료스핀

  10. Pron Videos表示:

    Di Indonesia, situs yang menyediakan layanan porno ilegal dengan video porno anak kecil adalah kejahatan berat yang melanggar undang-undang.

    Situs-situs ini tidak hanya merusak moral masyarakat, tetapi
    juga membahayakan masa depan anak-anak. Pemerintah melarang keras dan menindak tegas situs-situs semacam itu demi melindungi generasi muda.

  11. It is not my first time to pay a quick visit this website, i am visiting
    this website dailly and get good data from here every day.

  12. Wow, this paragraph is good, my younger sister is analyzing these things, so I am going to inform her.

  13. Lodibet表示:

    Time to unlock new levels and new skills Lodibet

  14. Профессиональный сервисный центр ремонт телефонов поблизости от меня цены на ремонт телефоно

  15. AgustinBougs表示:

    https://mexicanpharm24.pro/# purple pharmacy mexico price list
    п»їlegitimate online pharmacies india

  16. Haroldcox表示:

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

  17. Five Killer Quora Answers On Electric Fire Wall Mounted electric fire wall

  18. Обучение и поддержка операторов лазерных станков
    Мы не только продаем лазерные станки, но и обучаем ваших сотрудников их эффективной эксплуатации, а также оказываем поддержку на всех этапах работы.

    лазерная резка металла станок лазерные станки для резки металла .

  19. AgustinBougs表示:

    https://indianpharmdelivery.com/# indian pharmacy paypal
    india online pharmacy

  20. Garfield Lack表示:

    10 Myths Your Boss Has Concerning Electric Wall Mounted Fire Electric fire on the wall

  21. Diplomi_kfEn表示:

    продам диплом о высшем образовании orik-diploms.ru .

  22. AgustinBougs表示:

    https://mexicanpharm24.pro/# mexican drugstore online
    п»їlegitimate online pharmacies india

  23. Diplomi_hmEn表示:

    куплю диплом сделать orik-diploms.ru .

  24. Профессиональный сервисный центр сколько стоит ремонт смартфона ремонт смартфонов

  25. Гермес表示:

    I got this site from my friend who told me about this site and now this time I am browsing this
    web site and reading very informative posts at this place.

  26. If some one wants expert view about blogging and site-building then i advise him/her to pay a visit this weblog, Keep up the good work.

  27. KeithMup表示:

    7 simple secrets to eating the Mediterranean way
    kraken
    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.

  28. MichelJer表示:

    Новини https://u-misti.khmelnytskyi.ua актуальні новини Хмельницького, події міста. Корисна інформація для жителів Хмельницького та області

發佈留言

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