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,166,105 Responses

  1. The Most Powerful Sources Of Inspiration Of Motorcycle
    Accident Lawyers Motorcycle Accidents

  2. The IQ is the best completely dry natural herb vape I have tried.

    Here is my blog post; where can you buy plant based foods

  3. An All-Inclusive List Of Birth Defect Settlement Dos And Don’ts birth defect law firms

  4. The 10 Most Scariest Things About Private ADHD Assessment Leicester private adhd assessment Leicester

  5. Double Glazing Near Me Tools To Ease Your Daily Life
    Double Glazing Near Me Trick That Everyone Should Be Able To double Glazing near me (http://toolbarqueries.google.dk/)

  6. What You Should Be Focusing On Improving Window Replacement Window Replacement Glass

  7. Drugs information for patients. Effects of Drug Abuse.
    buy lyrica online cheap
    Everything information about medicines. Get information here.

  8. Medicine prescribing information. Drug Class.
    can i order olmesartan without dr prescription
    All what you want to know about medicine. Read information now.

  9. swap pdf表示:

    Ꭲhanks for finally writing abⲟut > JS 依照元素出現數量排序 – 馬老師 雲端研究室 swap pdf

  10. Meds information leaflet. Brand names.
    can you take lisinopril and norvasc at the same time
    Actual news about pills. Get information now.

  11. My brother suggested I would possibly like this web site. He used to be entirely right.

    This submit actually made my day. You cann’t consider just how a
    lot time I had spent for this information! Thanks!

  12. Here’s A Few Facts Concerning Window Repair Near window repair near me

  13. Drug information for patients. Short-Term Effects.
    can you get generic neurontin tablets
    Everything news about medicines. Read information now.

  14. Sherman表示:

    The Unspoken Secrets Of Mesothelioma Legal
    Question mesothelioma lawsuits, Sherman,

  15. You’ll Never Guess This 18 Wheeler Accident Law Firm’s Tricks 18 Wheeler accident law firm

  16. Hi colleagues, how is the whole thing, and what you desire to say concerning this paragraph, in my view its really
    awesome for me.

  17. Drugs information leaflet. Drug Class.
    how to buy cheap fluoxetine tablets
    Best about drug. Read now.

  18. Hi, i think that i saw you visited my web site thus i
    came to “return the favor”.I am trying to find things
    to enhance my website!I suppose its ok to use some of your ideas!!

  19. Drug information for patients. Brand names.
    zithromax price at zithrozpack
    Everything about medicine. Get information here.

  20. Medicine information sheet. Short-Term Effects.
    cost of aricept without insurance
    Some news about drug. Get here.

  21. The intelligence is the very best dry herb vegetable based vape juice I have actually attempted.

  22. Repairs To Upvc Windows Tools To Help You Manage Your Everyday LifeThe Only Repairs To
    Upvc Windows Trick That Everyone Should Learn repairs to upvc windows

  23. 1win вход表示:

    1win казино: играй и выигрывай, не упустите свой шанс!
    1win казино – место, где рождаются победы, играйте и выигрывайте без ограничений!
    1win казино: лучший выбор для азартных игр, начните игру прямо сейчас!
    1win казино: ваш путь к легким деньгам, получите удовольствие от азарта!
    1win казино – лучший выбор для азартных игр, получите удовольствие от азарта с 1win казино!
    1win зеркало https://populyarnoye-onlayn-kazino-belarusi.com/ .

  24. How Lost Ferrari Key Was The Most Talked About Trend In 2022
    Ferrari Key Programmer

  25. What’s The Current Job Market For Online Sites For Shopping In Uk Professionals Like?
    Online Sites For Shopping In Uk

  26. Replacement Upvc Door Handles Tools To Help You Manage Your Daily LifeThe One Replacement Upvc Door Handles Trick That Should Be Used By
    Everyone Know replacement upvc door handles

發佈留言

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