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,373,197 Responses

  1. Ten Bentley Keyss That Really Help You Live
    Better bentley key fob For sale

  2. What’s up to all, the contents existing at this site are in fact amazing for people knowledge, well,
    keep up the nice work fellows.

  3. Bill Greenup表示:

    This Is The Complete Guide To Audi Convenience Key audi car Key holder

  4. When some one searches for his necessary thing, thus he/she desires to be available that in detail, so that
    thing is maintained over here.

  5. Noble Gold has actually partnered with Equity Institutional as its custodian for custodianship and storage space.

    My website: businesses sales

  6. I like what you guys tend to be up too. This type of clever work and coverage!
    Keep up the fantastic works guys I’ve included you guys to
    blogroll.

  7. вывод из запоя в ростове-на-дону вывод из запоя в ростове-на-дону .

  8. Robby Till表示:

    You’ll Never Be Able To Figure Out This Double Single Bunk Bed’s Secrets Double single Bunk

  9. Excellent site you have got here.. It’s hard to find quality writing like yours these days.
    I truly appreciate people like you! Take care!!

  10. Armandoknot表示:

    Смешные картинки.
    Лучшие приколы!

  11. В магазине сейфов предлагают купить сейф где купить сейфы в москве

  12. Great work! That is the kind of information that should be shared across the web.
    Shame on the search engines for now not positioning this publish upper!
    Come on over and talk over with my web site .
    Thanks =)

  13. BarryDof表示:

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

  14. Francesco表示:

    Spot on with this write-up, I truly feel this site needs far more attention. I’ll probably be returning to read more,
    thanks for the advice!

  15. togel4D login表示:

    9 Things Your Parents Teach You About Togel4d Login togel4D login

  16. Профессиональный сервисный центр по ремонту планшетов в Москве.
    Мы предлагаем: замена тачскрина на планшете цена
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  17. Jacquelyn Chu表示:

    What’s The Current Job Market For Titration ADHD Medications Professionals?titration adhd medication (joyner-Mcculloch-2.technetbloggers.de)

  18. Guide To Replace Upvc Door Handle: The Intermediate Guide To Replace Upvc Door Handle replace upvc door Handle (lovewiki.faith)

  19. web tasarım表示:

    web tasarım

    Hi, I do think your website might be having browser compatibility problems.
    Whenever I take a look at your blog in Safari, it looks fine however when opening in Internet Explorer, it has some overlapping issues.
    I just wanted to provide you with a quick heads up!
    Other than that, great site!

  20. 1 win表示:

    Hello! I know this is kinda off topic however , I’d figured I’d ask.
    Would you be interested in exchanging links or maybe guest writing a blog article or vice-versa?
    My website discusses a lot of the same topics as yours and I feel we could greatly benefit from each other.
    If you happen to be interested feel free to send me an e-mail.
    I look forward to hearing from you! Great blog by the way!

  21. LeroyAcuff表示:

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

  22. uk88表示:

    Hmm is anyone else experiencing problems with the
    pictures on this blog loading? I’m trying to determine if its a problem on my end or if
    it’s the blog. Any responses would be greatly appreciated.

  23. Ken De Lissa表示:

    What Is Everyone Talking About Couches For Sale Right Now Couches For sale manchester

  24. Smart Aluminium Tilt And Turn Windows Tools To Improve Your Daily Life Smart Aluminium Tilt And Turn Windows Trick That Every Person Must Learn smart aluminium tilt And turn windows

  25. 17 Signs That You Work With Electric Wheelchairs Power Chair Near Me (http://Www.Stes.Tyc.Edu.Tw/)

  26. BarryDof表示:

    https://ozempic.art/# buy cheap ozempic

  27. Just want to say your article is as astonishing.
    The clearness for your put up is just excellent and that i could assume you are a professional on this subject.
    Well with your permission allow me to take hold of your feed
    to keep up to date with forthcoming post. Thank you 1,000,000 and please carry
    on the rewarding work.

發佈留言

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