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,365,240 Responses

  1. Barb Soukup表示:

    What’s The Job Market For Big Clay Chiminea Professionals?big clay chiminea (Keith)

  2. Bokep Indo表示:

    I was recommended this web site by my cousin. I am not sure whether this post is written by him as no
    one else know such detailed about my problem.
    You are amazing! Thanks!

  3. Jeremypag表示:

    buy ozempic pills online ozempic ozempic online

  4. 10 Wrong Answers For Common Best Double Bunk Beds Questions Do You Know The Correct Answers?bunk Bed Usa

  5. LeroyAcuff表示:

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

  6. RamonRek表示:

    buy ozempic: ozempic – buy ozempic

  7. Wow, this report very strike the nail upon the brain! I’ve been having
    difficulties with this make any difference for a long time
    and it’s therefore new towards watch an individual incredibly dive deep into
    the predicament and present convenient services. The illustrations oneself available had been surprisingly
    relatable and I found out myself nodding together as I study throughout them.

    One particular matter that incredibly resonated with me was the reality oneself generated concerning the great importance of self-treatment.
    It’s hence uncomplicated toward receive stuck up
    in just the working day-toward-working day grind and ignore
    our private health and fitness. Yet as on your own rightly pointed out,
    using the season towards recharge and prioritize our psychological and bodily physical
    fitness is very important if we have to have toward be
    our least complicated selves. I’m unquestionably
    shifting towards consider utilizing some of the guidelines oneself
    shared. Thank on your own for this enlightening and inspiring short article!

  8. LeroyAcuff表示:

    Профессиональный сервисный центр мастерская по ремонту телефонов ремонт телефон

  9. BarryDof表示:

    https://ozempic.art/# Ozempic without insurance

  10. Where Do You Think Replace Panel In Upvc Door One Year From This Year?upvc door panel with cat flap fitted; https://botdb.win/wiki/11_Ways_To_Completely_Redesign_Your_Replacing_A_Upvc_Door_Panel,

  11. ArthurReile表示:

    Фотофабрика кухонных гарнитуров в Санкт-петербурге – это чемодан фундаментальный партнер в создании кухонных интерьеров. Мы работаем сверху исследованию, изготовлении также установке высококачественных кашеварных гарнитуров, коим сочетают на себе стиль, работоспособность да долговечность. Наша назначение – уделить покупателям индивидуальные резолюции, созданные раз-два учётом ихний пожеланий равным образом необходимостей, чтоб каждая шакша начала уютным и еще спокойным площадью чтобы века да творчества http://tivokya0kuhnishki.ru/.

  12. BarryDof表示:

    https://rybelsus.shop/# rybelsus pill

  13. BarryDof表示:

    https://rybelsus.shop/# buy semaglutide online

  14. Nearby表示:

    Seven Explanations On Why Car Diagnostics Near Me Is So
    Important Nearby

  15. Guide To Saab Replacement Keys Uk: The Intermediate Guide The Steps To Saab Replacement Keys Uk Saab replacement keys uk

  16. tante bugil表示:

    Having read this I thought it was very enlightening.
    I appreciate you spending some time and energy to put this informative article together.
    I once again find myself spending a significant amount of time both reading and posting
    comments. But so what, it was still worthwhile!

  17. BarryDof表示:

    https://ozempic.art/# buy ozempic pills online

  18. RamonRek表示:

    buy semaglutide online: buy rybelsus online – cheapest rybelsus pills

  19. Quantum Edex表示:

    For latest information you have to pay a visit world wide
    web and on web I found this website as a most excellent web site for newest updates.

  20. Buddy表示:

    4 Dirty Little Secrets About Audi Key Replacement And The Audi Key Replacement Industry replacement audi a4
    key, Buddy,

  21. Get Rid Of U Shaped Sofa Leather: 10 Reasons Why You No Longer Need It small U shaped sofa

  22. See What ADHD Treatment In Adults Tricks The Celebs Are Making Use Of Adhd treatment In adults

  23. Shasta Heysen表示:

    Why Do So Many People Want To Know About L Shape Leather Sofa?L Shaped Couch

  24. LeroyAcuff表示:

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

  25. Hershel Nolan表示:

    “The Upvc Doors Repair Awards: The Top, Worst, Or The Most Bizarre Things We’ve Seen Upvc Doors Repairs Near Me

  26. Why You Should Focus On Improving Audi Key Replacement audi car key cover

  27. Frankevild表示:

    https://ozempic.art/# ozempic

  28. 20 Tools That Will Make You Better At Rollator 3 In 1 high-quality rollator (Leslee)

  29. What’s up i am kavin, its my first occasion to commenting anywhere, when i read this article i thought i could also create comment due to this good paragraph.

發佈留言

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