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,477,506 Responses

  1. Don’t Be Enticed By These “Trends” About Private Adult Adhd Assessment adhd assessment tools for adults online

  2. Guide To Situs Togel Dan Slot Terpercaya: The Intermediate Guide In Situs Togel Dan Slot Terpercaya situs Togel dan slot Terpercaya

  3. BrandonJer表示:

    indian pharmacy paypal mail order pharmacy india top 10 pharmacies in india

  4. A Trip Back In Time How People Talked About Togel4d 20 Years Ago toto4D

  5. sex表示:

    I always emailed this website post page to all my associates, since if like
    to read it afterward my links will too.

  6. Join Taya365 and explore a world of thrilling online games with great chances to win big rewards.

  7. 10 Wrong Answers To Common Mesothelioma Lawyer Questions Do You Know The Right Answers? Mesothelioma Settlement

  8. BrandonJer表示:

    reputable mexican pharmacies online reputable mexican pharmacies online reputable mexican pharmacies online

  9. Sazrjuq表示:

    Как официально приобрести аттестат 11 класса с минимальными затратами времени

    forum.electrostal.com/index.php?PHPSESSID=8q6fhbbafrc9dcuvg3cnjtc957&topic=85808.120

  10. You’ll Never Guess This Comfy Couches For Sale’s Tricks comfy couches for sale

  11. slot mpo表示:

    Howdy I am so excited I found your site, I really found you by error, while I was searching
    on Yahoo for something else, Nonetheless I am here now and
    would just like to say thanks a lot for a incredible post and
    a all round interesting blog (I also love the theme/design), I don’t have time to browse it all at the
    moment but I have book-marked it and also added your RSS feeds,
    so when I have time I will be back to read much more, Please
    do keep up the superb b.

  12. kenya eta faq表示:

    Link exchange is nothing else except it is only placing the other person’s weblog
    link on your page at appropriate place and other person will also do same in favor of you.

  13. Genuinely no matter if someone doesn’t know afterward its up to other people that they will help, so here it happens.

  14. Asbestos Attorney Lawyer Mesothelioma Tools To
    Make Your Daily Lifethe One Asbestos Attorney Lawyer
    Mesothelioma Trick That Every Person Should Know
    Asbestos attorney

  15. Electric Powered Wheelchairs Tips From The Most Successful In The Industry electric light weight wheelchair (Willard)

  16. 16 Facebook Pages That You Must Follow For Attorneys
    For Asbestos Exposure-Related Businesses asbestos attorney

  17. I love your blog.. very nice colors & theme.
    Did you design this website yourself or did you hire someone
    to do it for you? Plz reply as I’m looking to construct my own blog and would like to find out where u got
    this from. thanks a lot

  18. Are You Responsible For The Couch With Chaise Budget?10 Ways To Waste Your Money Chaise lounge sofa

  19. AgustinBougs表示:

    https://mexicanpharm24.pro/# mexican rx online
    best online pharmacy india

  20. Ten French Style Fridge Freezers That Really Improve Your Life french Style fridge freezers

  21. My programmer is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the costs.
    But he’s tryiong none the less. I’ve been using WordPress on a variety
    of websites for about a year and am anxious about switching to another
    platform. I have heard fantastic things about blogengine.net.
    Is there a way I can import all my wordpress posts into it?
    Any kind of help would be greatly appreciated!

  22. Guide To Sleeper Sofa With Chaise: The Intermediate Guide In Sleeper Sofa With Chaise sleeper sofa with chaise (Denny)

  23. Gallerix表示:

    It’s perfect time to make some plans for the future and it is time to be happy.
    I have read this put up and if I may just I want
    to recommend you some attention-grabbing issues or suggestions.
    Perhaps you could write subsequent articles referring
    to this article. I wish to read even more issues approximately it!

  24. Harrison表示:

    The History Of Misted Double Glazed Units misted windows near me (Harrison)

  25. Galen Luis表示:

    9 Lessons Your Parents Taught You About Togel4d Login Togel4D login

  26. Когда вы начинаете играть на сайте казино Пин Ап, важно прочитать все положения и условия перед регистрацией.

  27. Silas Kleiman表示:

    The People Who Are Closest To Electric Personal Transporters Uncover Big Secrets 4 Wheel Mobility Scooter Electric Scooters

  28. How Much Do Land Rover Discovery Key Replacement Experts
    Earn? land rover Keys replacement

  29. Diplomi_ijEn表示:

    купить аттестат об окончании 11 классов orik-diploms.ru .

發佈留言

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