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,180,521 Responses

  1. 10 Healthy Integrated Fridge Freezer Side By Side Habits https://www.36035372.xyz

  2. bokep jepang表示:

    Hi there! I know this is kinda off topic however I’d figured I’d ask.
    Would you be interested in trading links or maybe guest authoring a blog article or vice-versa?
    My blog covers a lot of the same topics as yours and I think we could greatly
    benefit from each other. If you’re interested feel free to shoot me an email.
    I look forward to hearing from you! Great blog by the way!

  3. situs porno表示:

    Hello, I check your blog like every week. Your writing
    style is witty, keep doing what you’re doing!

  4. Bookmarks表示:

    Thank you for any other wonderful article. The place else may just anybody get that type of information in such an ideal approach of writing?
    I have a presentation next week, and I’m on the look for such information.

    Feel free to surf to my homepage Bookmarks

  5. Somebody necessarily lend a hand to make severely articles I’d
    state. This is the first time I frequented your web page and so far?

    I amazed with the research you made to make this actual post incredible.
    Wonderful process!

    my web page best seo company in jalandhar

  6. Dor77表示:

    Greate pieces. Keep writing such kind of information on your page.
    Im really impressed by it.
    Hello there, You’ve done a fantastic job. I will definitely digg
    it and individually recommend to my friends. I am confident they’ll be benefited from this website.

    Feel free to surf to my website … Dor77

  7. Как выбрать лучшие тактичные штаны для активного отдыха, которые подчеркнут вашу индивидуальность.
    Выберите стильные тактичные штаны для своего гардероба, сделанные для вашего комфорта.
    Советы по выбору тактичных штанов, чтобы выглядеть стильно в любой ситуации.
    Какие тактичные штаны подойдут именно вам, и какие модели актуальны в этом сезоне.
    Тактичные штаны: выбор современного мужчины, и какие модели стоит выбрать для уникального стиля.
    штани тактичні з наколінниками https://vijskovitaktichnishtanu.kiev.ua/ .

  8. Hey there, You’ve done an incredible job. I’ll certainly
    digg it and personally suggest to my friends. I am sure they will be benefited
    from this site.

  9. ConradTum表示:

    Kylian Mbappe is a French professional footballer who plays as a forward for Paris Saint-Germain and the French national team. Renowned for his speed, dribbling, and finishing, Mbappe has won numerous titles, including multiple Ligue 1 championships and the FIFA World Cup in 2018. Find out more about him here – https://kylianmbappe.paris-saint-germain-ar.com/

  10. 30 Inspirational Quotes On Built-In Fridge http://www.36035372.xyz

  11. Who Is 18 Wheeler Accident Law Firm And Why You Should Be
    Concerned 18 wheeler accident lawyer

  12. Piano verhuisbedrijf kiezen

  13. Guide To Best Medication For ADHD: The Intermediate Guide In Best Medication For
    ADHD best Medication for adhd

  14. It’s remarkable in support of me to have a web site, which is
    useful for my knowledge. thanks admin

  15. Source URL表示:

    I think this is among the most vital info for me. And i am glad reading your article.
    But wanna remark on few general things, The site style is wonderful,
    the articles is really excellent : D. Good job, cheers

  16. You’ll Never Guess This Fela Attorneys Near Me’s Tricks Fela Attorneys Near Me

  17. В современном мире телефоны стали неотъемлемой долею нашей повседневной жизни

  18. The Top Reasons People Succeed In The Coffee Machine Pod Industry coffee machines industrial

  19. need to be reminded, that not all disciplines and coins are NFT,
    so https://playdoge.io/, always need to take into account that little all coins exist on the blockchain.

  20. nitrous oxide表示:

    Terrific posts. Thanks a lot.

發佈留言

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