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,239,031 Responses

  1. Guide To Pull Out Couches For Sale: The Intermediate Guide Towards Pull Out Couches For Sale Pull Out couches for sale

  2. The Reasons Are Tilt And Turn Windows Any Good Is Everywhere This Year Tilt And Turn Windows Opening Outwards

  3. ClydePab表示:

    matadorbet bid: matadorbet – matadorbet.bid

  4. Uazrvxh表示:

    Купить диплом старого образца, можно ли это сделать по быстрой схеме?

    kira-marie.com/kupit-attestat-za-9-klass-v-bishkeke.html

  5. Paragraph writing is also a excitement, if you be
    acquainted with afterward you can write otherwise
    it is complicated to write.

  6. I really like reading an article that can make people think.
    Also, thank you for allowing for me to comment!

  7. 11 “Faux Pas” That Are Actually Okay To Use With Your Replacement Key
    For Audi audi key blade

  8. It Is The History Of Asbestos Cancer Law Lawyer Mesothelioma Settlement In 10 Milestones Mesothelioma Lawsuits

  9. Diplomi_xher表示:

    дипломы училища купить дипломы училища купить .

  10. Item upgrade表示:

    5 Killer Quora Answers On Item Upgrade Item upgrade

  11. Hi, every time i used to check website posts
    here in the early hours in the daylight, as i like to learn more and more.

  12. What’s The Current Job Market For Accident & Injury Lawyers Professionals?

    accident & injury lawyers

  13. Diplomi_dmer表示:

    купить диплом мединститута купить диплом мединститута .

  14. 20 Resources To Make You More Efficient At Sprt Toto
    4d 먹튀검증 커뮤니티

  15. 10 Sports Toto Prizes Meetups You Should Attend
    스포츠토토 사이트

  16. It’s awesome in favor of me to have a web site, which is beneficial in favor of my experience.
    thanks admin

  17. Ten Things Everyone Misunderstands About The Word “Best Self Propelled Wheelchair”
    best self propelled wheelchair Uk

  18. Uazrzia表示:

    Как приобрести диплом техникума с минимальными рисками
    logomotiv.hu/kupit-attestat-za-11-klass-nedorogo-v-irkutske.html

  19. Derekfar表示:

    ultrabet guncel: ultrabet – ultrabet

  20. Video Downloadr, Instagram video indirmek için en popüler
    araçlardan biridir.

  21. Geraldvef表示:

    Разработка лендингов в студии в Москве осуществляется с учетом современных маркетинговых стратегий и требований рынка. К основным услугам добавляются: аудит и анализ конверсии, продвижение в поисковых системах, контентное наполнение, настройка CRM и профессиональная техническая поддержка разработка лендинг страниц

發佈留言

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