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,576,376 Responses

  1. Good blog you have got here.. It’s hard to find excellent writing like yours nowadays.

    I honestly appreciate people like you! Take care!!

  2. Amazing lots of useful information!

  3. Узнай все о варикоцеле симптомы признаки варикоцеле

  4. Jeepin.Com表示:

    Hey very spectacular blog!! Chap .. Remarkable .. Amazing .. I will bookmark your blog and take the feeds additionally�I am delighted to locate so numerous advantageous knowledge present in the post, we want increase more methods on this regard, thank you for distribution.

    My webpage http://jeepin.com/forum/member.php?u=152770

  5. Nikefut表示:

    dark web search engine deep web sites dark web link

  6. Узнай все о чем опасно варикоцеле заболевание варикоцеле

  7. Узнай все о варикоцеле яичка у мужчины варикоцеле яичка

  8. Blakesmema表示:

    изготовление кухни на заказ — Качественное и профессиональное изготовление кухонь по индивидуальным проектам.

  9. StevenNub表示:

    where buy generic clomid prices: rex pharm – order clomid without rx

  10. leahsilRak表示:

    По моему мнению Вы не правы. Я уверен. Могу это доказать. Пишите мне в PM, пообщаемся.
    Прочитайте о том, как зарегиться и организовать сайт. В панели управления переместитесь на вкладку “Неактивные” выбирайте в разделах модуль каталог частных объяв и предприятий, объявление доска объявлений нажмите по нему и нажимайте кнопку “Активировать модуль”.

  11. StevenNub表示:

    amoxicillin 500 mg tablet price: Amoxicillin for sale – amoxicillin 500mg price canada

  12. StevenNub表示:

    dapoxetine online: priligy – buy dapoxetine online

  13. DavidShoks表示:

    GasDank is your go-to for ordering weed online in Canada. We are a safe and discreet marijuana mail order service based in Toronto, Ontario, also offering same-day delivery throughout the GTA http://astral-pro.com/go?https://gasdank.com/store-locator/

  14. BrandenSlomy表示:

    how can i get generic clomid price: rexpharm – how to get cheap clomid without a prescription

  15. StevenNub表示:

    can i buy amoxicillin online: com pharm – buy amoxicillin over the counter uk

  16. StevenNub表示:

    amoxicillin 500mg buy online uk: cheap amoxil – amoxicillin without a prescription

  17. Learn More表示:

    Hey there! 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 blog goes over a lot of the same subjects as yours and I believe we
    could greatly benefit from each other. If you happen to be
    interested feel free to shoot me an email. I look forward to hearing from you!
    Terrific blog by the way!

  18. Bradleygoath表示:

    max pharm priligy maxpharm dapoxetine online

  19. Undeniably consider that which you said. Your favorite justification appeared to be
    at the internet the simplest thing to take note of. I say to you, I definitely get irked whilst other people think about concerns that they just do not recognize about.
    You managed to hit the nail upon the highest and defined out the whole thing without having side-effects , people
    could take a signal. Will probably be again to get more.
    Thanks

  20. Greetings from California! I’m bored at work so I decided to check out your blog on my iphone during lunch break.

    I really like the knowledge you present here and can’t wait to take a look when I get home.
    I’m amazed at how quick your blog loaded on my phone ..
    I’m not even using WIFI, just 3G .. Anyways, fantastic blog!

  21. Bradleygoath表示:

    generic clomid pills cheap clomid generic clomid pills

  22. Lester Flores表示:

    I love how many tutorials are available now for fixing common phone problems! If you’re interested in learning more, check out the awesome content at ipad repair

  23. LeonardKnism表示:

    flowers777.ru — Надежный поставщик кухонь в Санкт-Петербурге.

  24. Bradleygoath表示:

    dapoxetine online priligy maxpharm buy priligy

發佈留言

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