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

  1. WillieRap表示:

    Cheapest online pharmacy: Online pharmacy USA – online pharmacy no prescription needed

  2. Davidmoits表示:

    MegaIndiaPharm: MegaIndiaPharm – MegaIndiaPharm

  3. Dennisbem表示:

    Зависимость – это сложное испытание, с которым сталкиваются люди во всём мире. Ежедневные стрессы, проблемы в семье и на работе, финансовые трудности часто становятся почвой для развития пагубных привычек, таких как алкоголизм, наркомания и игромания. Медицинский центр «Второй Шанс» предоставляет помощь тем, кто хочет избавиться от этих состояний, вернуть здоровье и научиться жить без разрушительных зависимостей.
    Разобраться лучше – vyvod iz zapoya vrach na dom sankt-peterburg

  4. 1 vin_vtSi表示:

    скачать 1win официальный сайт http://bbcc.com.kg/ .

  5. 10 Of The Top Mobile Apps To Use For Buy Driving License Online
    KöPa A2 Körkort

  6. MarkWat表示:

    Всем привет! Подскажите, где найтиполезные блоги о кредитах? Сейчас читаю – https://kamdengi.ru

  7. 1 vin_iaSi表示:

    1win регистрация https://www.bbcc.com.kg .

  8. After I originally commented I appear to have clicked
    on the -Notify me when new comments are added- checkbox and
    from now on every time a comment is added I receive 4 emails with the exact same
    comment. Perhaps there is a means you are able to remove me from that service?

    Cheers!

  9. 1 vin_yqSi表示:

    вывод средств 1win http://bbcc.com.kg .

  10. Charleskepsy表示:

    online pharmacy no prescription https://discountdrugmart.pro/# discount drugs

  11. Asking questions are really pleasant thing if you are not understanding anything totally,
    but this paragraph gives fastidious understanding even.

  12. MichaelIncap表示:

    dark web sites links https://github.com/darknetmarketslinks/darknetmarketlinks – tor market url dark web websites

  13. WillieRap表示:

    easy canadian pharm: easy canadian pharm – canadian pharmacy scam

  14. It’s actually very complicated in this full of activity life to listen news on TV, therefore I only use internet for that reason, and obtain the hottest information.

  15. Right now it looks like Drupal is the preferred blogging platform out there right now.

    (from what I’ve read) Is that what you’re using on your blog?

  16. WillieRap表示:

    xxl mexican pharm: xxl mexican pharm – buying prescription drugs in mexico online

  17. This design is wicked! You definitely know how to keep a
    reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Excellent job.
    I really enjoyed what you had to say, and more than that, how you
    presented it. Too cool!

  18. MichaelIncap表示:

    the dark internet https://github.com/darknetmarketslinks/darknetmarketlinks – tor market links drug markets dark web

  19. Michaelvof表示:

    Maximizing Profits with 1inch Exchange
    In the fast-paced world of cryptocurrency, every second counts. 1inch Exchange offers a powerful solution for traders looking to optimize their crypto transactions. By aggregating the best deals across various decentralized exchanges (DEXs), 1inch ensures users get the most value for their trades.
    1inch swap
    What is 1inch Exchange?
    1inch Exchange is a decentralized exchange aggregator. It searches multiple DEXs to find the most efficient path for your trade, thus minimizing costs and maximizing returns. By splitting your transaction into parts and executing them across different platforms, 1inch achieves the best possible market rates.

    Key Benefits of Using 1inch Exchange
    Cost Efficiency: By seeking the best rates across multiple platforms, 1inch saves you money on each transaction.
    Security: Operating on a decentralized network means that your assets are secure and you maintain control of your keys.
    Liquidity: Access a vast pool of liquidity across numerous exchanges, ensuring that your trades are executed quickly and with minimal slippage.
    How Does 1inch Work?
    1inch deploys a sophisticated algorithm that splits your trade across multiple exchanges. This process uses smart contracts to ensure every part of the transaction is executed seamlessly and securely. 1inch’s pathfinder algorithm analyzes multiple liquidity sources within seconds to find the best exchange rates for your trade.

    Getting Started with 1inch
    Getting started with 1inch Exchange is easy. Follow these simple steps:

    Visit the 1inch website and connect your digital wallet.
    Select the token you wish to trade and the token you want to receive.
    1inch displays the best available rates and allows you to execute the trade directly from the platform.
    Conclusion
    1inch Exchange is an invaluable tool for cryptocurrency traders looking to enhance their trading efficiency. By securing the best rates and offering robust security measures, 1inch stands out as a top choice for optimizing crypto swaps. Explore 1inch today and take your trading to the next level.

  20. First of all I want to say terrific blog!
    I had a quick question in which I’d like to ask if you do not mind.
    I was curious to know how you center yourself and clear your thoughts before writing.
    I have had a tough time clearing my thoughts in getting my thoughts out.
    I do take pleasure in writing however it just seems like the first 10 to 15 minutes are
    usually lost simply just trying to figure out how to begin. Any recommendations or tips?
    Thanks!

  21. 1win_evOa表示:

    1win официальный сайт скачать http://fabc.com.kg .

  22. Ten Things You Learned At Preschool To Help You Get A Handle On Gas Engineer Newport Pagnell Newport Pagnell Gas Safe Engineers

  23. 1win_zlOa表示:

    1win зайти fabc.com.kg .

發佈留言

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