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,165,523 Responses

  1. 5 Examples Of Online Products Projects For Every Budget Hockey Stickhandling Trainer

  2. Good article. I definitely love this website.
    Continue the good work!

  3. Auto Accident Lawyer 101:”The Ultimate Guide For Beginners Auto Accident lawsuits

  4. Genuine HGH Rewards (NewULife Hgh Gel Not Evaluated Yet).

    Here is my blog … rot content meaning

  5. Medicines information sheet. Generic Name.
    where to buy generic ventolin price
    Some what you want to know about meds. Get information now.

  6. Josephton表示:

    The world’s most liveable cities for 2024
    порно секс жесток

    It’s considered among the most beautiful cities in the world to visit, and it seems that Vienna may also be an unbeatable place to live.

    The Austrian city has been crowned the most liveable city in the world yet again in the annual list from the Economist Intelligence Unit (EIU), which was released today.

    The EIU, a sister organization to The Economist, ranked 173 cities across the globe on a number of significant factors, including health care, culture and environment, stability, infrastructure and education.

    Vienna topped the list for the third consecutive year, receiving “perfect” scores in four out of five of the categories — the city was marked lower for culture and environment due to an apparent lack of significant sporting events.
    Just behind the Austrian capital, Denmark’s Copenhagen retained its second place position, while Switzerland’s Zurich moved up from sixth place to third on the list.

    Australia’s Melbourne fell from third to fourth place, while Canadian city Calgary tied for fifth place with Swiss city Geneva.

    Canada’s Vancouver and Australia’s Sydney were in joint seventh place, and Japan’s Osaka and New Zealand’s Auckland rounded out the top 10 in joint ninth place.

  7. 15 Top Twitter Accounts To Learn More About Workers Compensation Legal Workers’ compensation Lawsuit

  8. What Is Upvc Windows Repairs’s History? History Of Upvc
    Windows Repairs Repairing upvc Windows

  9. memek enak表示:

    I’m curious to find out what blog platform you have been utilizing?
    I’m experiencing some minor security issues with my latest blog and I’d like to find something more
    risk-free. Do you have any recommendations?

  10. Plant-based vapes have a host of possible benefits.

    my website … what beers are vegan uk

  11. crypto boss表示:

    И третий плюс – практически мгновенные операции с
    деньгами, а комиссия совсем смешная,
    практически незаметна.

  12. Bookmarks表示:

    The vapor and flavor quality is additionally excellent.

    Here is my blog post; Bookmarks

  13. Medicine information. Generic Name.
    can i order generic arimidex
    Everything trends of pills. Get now.

  14. Medicament information for patients. Generic Name.
    can i get cheap norvasc prices
    Actual information about drug. Get information now.

  15. It’s impressive that you are getting thoughts from this
    paragraph as well as from our dialogue made at this time.

  16. USP human growth hormonal agent (somatropin).

    My homepage; ai headshot generator free website

  17. You’ll Be Unable To Guess Online Shopping Sites Top 7’s Benefits Online Shopping Sites top 7

  18. You could file a lawsuit anyone who’s Asbestos attorney-related products have caused harm.
    After years of litigation companies in the asbestos
    industry have been bankrupted and set up asbestos bankruptcy trusts.

  19. USP human development hormone (somatropin).

    Here is my site … list of disability benefits

  20. cassylawn表示:

    The Reason Why Lung Cancer Asbestos Mesothelioma In 2023 Is
    The Main Focus Of All People’s Attention. 2023 cassylawn

  21. The 10 Most Terrifying Things About Which Is Best For Online Grocery
    Shopping which is Best for online grocery shopping

  22. They have products to sell or services to supply.

    Check out my web site: types of ssa disability benefits

  23. thabetrent表示:

    It’s a shame you don’t have a donate button! I’d without a doubt donate to
    this brilliant blog! I suppose for now i’ll settle for book-marking and adding your
    RSS feed to my Google account. I look forward to
    fresh updates and will share this blog with my Facebook group.

    Chat soon!

  24. In this situation, the life insurance policy company’s cash.

    My homepage … motion graphics web

  25. Portable vaporizers make use of batteries as a source of
    power.

    Feel free to surf to my blog :: where to buy plant based meals

發佈留言

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