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,424,305 Responses

  1. LeroyBak表示:

    medication from mexico pharmacy mexico pharmacy purple pharmacy mexico price list

  2. LeroyBak表示:

    indian pharmacy paypal Indian pharmacy to USA online shopping pharmacy india

  3. The Most Worst Nightmare About Folding Treadmill With Incline Be Realized small
    Treadmill incline (squareblogs.net)

  4. Williamagric表示:

    canadian drug https://indianpharm24.pro/# Online medicine order

  5. Jamesses表示:

    Познакомьтесь небольшой нашим профессиональным коллективом, который создаёт уникальную мебель, воплощая ваши мечты в течение реальность https://cehitae2kuhnishki.ru.

  6. 10 Tell-Tale Signals You Need To Know Before You
    Buy Mesothelioma Asbestos Lawyers mesothelioma attorney

  7. Drugs information for patients. Drug Class.
    can i purchase chlorpromazine without dr prescription
    All trends of medication. Read information now.

  8. BrandonSaisy表示:

    indianpharmacy com: Order medicine from India to USA – п»їlegitimate online pharmacies india

  9. LeroyBak表示:

    cheapest online pharmacy india India pharmacy delivery top 10 pharmacies in india

  10. Guide To Large Tilt And Turn Windows: The Intermediate Guide In Large
    Tilt And Turn Windows Large tilt and turn windows

  11. The Secret Secrets Of Under Counter Wine Fridge slim wine Refrigerator

  12. Williamagric表示:

    ed medications online http://pharm24.pro/# best drugs for erectile dysfunction

  13. I loved as much as you will receive carried out right here.
    The sketch is tasteful, your authored material stylish.
    nonetheless, you command get got an edginess over that you
    wish be delivering the following. unwell unquestionably come more formerly again as exactly
    the same nearly very often inside case you shield this increase.

  14. buy hacklink表示:

    buy cgild porn instagram best services.

  15. LeroyBak表示:

    buying prescription drugs in mexico online mexican pharm 24 buying prescription drugs in mexico

  16. DevonPhack表示:

    http://indianpharm24.pro/# indian pharmacy paypal
    male enhancement pills

  17. Shenasname.Ir表示:

    Hire Auto Accident Attorneys 101: Your Ultimate Guide For Beginners Lawyer Car Accidents (Shenasname.Ir)

  18. find out more表示:

    Appreciate this post. Let me try it out.

  19. ChrisUnuse表示:

    Found this article that’s worth reading hope you enjoy http://forum.csharing.org/viewtopic.php?f=2&t=604

  20. jilbab hot表示:

    Great article, totally what I was looking for.

  21. Burton表示:

    I’m really loving the theme/design of your blog.
    Do you ever run into any browser compatibility problems? A number of my blog readers have
    complained about my blog not working correctly in Explorer but looks great in Chrome.
    Do you have any advice to help fix this problem?

  22. 5 Qualities People Are Looking For In Every Adult Treatment For ADHD Online adhd Treatment

  23. Jorgeagopy表示:

    buying from online mexican pharmacy: mexico pharmacy – medication from mexico pharmacy

  24. BryanLam表示:

    Hello!

    Do you want to become the best SEO specialist and link builder or do you want to outpace your competitors?

    Premium base for XRumer
    $119/one-time
    Get access to our premium database, which is updated monthly! The database contains only those resources from which you will receive active links – from profiles and postings, as well as a huge collection of contact forms. Free database updates. There is also the possibility of a one-time purchase, without updating the databases, for $38.

    Fresh base for XRumer
    $94/one-time
    Get access to our fresh database, updated monthly! The database includes active links from forums, guest books, blogs, etc., as well as profiles and activations. Free database updates. There is also the possibility of a one-time purchase, without updating the databases, for $25.

    GSA Search Engine Ranker fresh verified link list
    $119/one-time
    Get access to our fresh database, updated monthly! The fresh database includes verified and identified links, divided by engine. Free database updates. There is also the possibility of a one-time purchase, without updating the databases, for $38.

    GSA Search Engine Ranker activation key
    $65
    With GSA Search Engine Ranker, you’ll never have to worry about backlinks again. The software creates backlinks for you 24 hours a day, 7 days a week. By purchasing GSA Search Engine Ranker from us, you get a quality product at a competitive price, saving your resources.

    To contact us write to Telegram: https://t.me/DropDeadStudio

  25. This is really interesting, You’re a very skilled blogger.
    I’ve joined your rss feed and look forward to seeking more of your excellent post.

    Also, I have shared your website in my social networks!

    Also visit my blog :: RandM Tornado 9000

發佈留言

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