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,377,102 Responses

  1. Searching for high-class Lahore call girls?

    We provide premium options.

  2. sarang777表示:

    Does your site have a contact page? I’m having trouble locating it but, I’d like to send you an email.
    I’ve got some ideas for your blog you might be interested in hearing.

    Either way, great website and I look forward to seeing it improve over time.

  3. click now表示:

    I was wondering if you ever considered changing the page layout of your blog?

    Its very well written; I love what youve got to say.
    But maybe you could a little more in the way of content so people could connect with
    it better. Youve got an awful lot of text for only having 1 or two
    pictures. Maybe you could space it out better?

  4. Edwin Harper表示:

    Excited about learning new ways improving ventilation through strategic placements described here!!!! `#` `#` roofing company

  5. Davogesta表示:

    В среде Kraken ваша безопасность и confidentiality are in focus. Эта онлайн-площадка offers convenient access к various services, которые гарантируют maximum privacy. Здесь правила обычного интернета не действуют, что allows you freely use интернет-услугами. Кракен ссылка

  6. http://localmap2.theseo.co.il
    SEO co | קידום אתרים בגוגל | שיווק אורגני

    I constantly spent my half an hour to read this website’s
    content every day along with a cup of coffee.

  7. Five Killer Quora Answers On Robot Vacuum Cleaner Best robot vacuum cleaner Best

  8. JacobLoody表示:

    http://ftbabrau.ru/ – проектирование и изготовление кухонь для вашего дома.

  9. There are various tools and websites that claim to allow users to view private Instagram profiles, but it’s important to retrieve these when caution. Many of these tools how can you view private instagram accounts be unreliable, may require personal information,
    or could violate Instagram’s terms of service. Additionally, using such tools can compromise your own security or lead
    to scams. The safest and most ethical mannerism to view a private profile is to send a follow request directly
    to the user. Always prioritize privacy and esteem in your online interactions.

  10. Play Baccarat Online – Benefits Of Playing The Game On The Web 에볼루션 데빌데모 (http://delphi.larsbo.org/)

  11. нарколог вывод из запоя [url=https://aktivnoe.forum24.ru/?1-2-0-00000092-000-0-0-1730831813]нарколог вывод из запоя [/url] .

  12. JacobLoody表示:

    http://www.ftbabrau.ru – стильные решения для кухни любой сложности.

發佈留言

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