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,247,401 Responses

  1. BrandenSlomy表示:

    buy amoxicillin online without prescription: Com Pharm – where can you buy amoxicillin over the counter

  2. Купить дапоксетин без рецептов в Санкт-Петербурге с доставкой https://spb-generic.ru/poxet большой выбор
    препаратов для мужчин производства Индии в наличии по выгодным ценам

  3. khelo 365表示:

    You’re so awesome! I do not believe I’ve read through something like that before.
    So great to discover someone with a few unique thoughts on this subject.
    Really.. thank you for starting this up. This site is something
    that is required on the internet, someone with a little originality!

  4. Does your website have a contact page? I’m having problems locating it but,
    I’d like to shoot you an email. I’ve got some recommendations for your blog you
    might be interested in hearing. Either way, great site and I look forward to seeing it develop over
    time.

  5. Yesterday, while I was at work, my cousin stole my iPad and tested
    to see if it can survive a forty foot drop, just so she can be a
    youtube sensation. My iPad is now destroyed and she
    has 83 views. I know this is totally off topic but I had to share it with someone!

  6. Klonopin USA表示:

    Great post. I waѕ checking continuously this weblog and I am
    impressed! Extremely helpful іnformation speсifically tһe remaining phase 🙂 Ӏ takе care of sᥙch info a lot.

    Ι useԁ to be loоking foг thiѕ paгticular info fοr a long time.

    Thanks and good luck.

    Here is my site; Klonopin USA

  7. Every weekend i used to pay a quick visit this web page, as i
    want enjoyment, for the reason that this this site conations really
    pleasant funny material too.

  8. BrandenSlomy表示:

    buy priligy max pharm: max pharm – Priligy tablets

  9. vegan protein表示:

    We stumbled over here by a different website and thought I might check things out.
    I like what I see so now i’m following you. Look forward to looking over your
    web page repeatedly.

  10. BrandenSlomy表示:

    how to get prednisone tablets: cheap prednisone – generic prednisone 10mg

  11. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point.
    You obviously know what youre talking about, why waste your intelligence on just posting videos to your site when you could be giving us something enlightening to read?

  12. Hi there, I discovered your site by means
    of Google at the same time as looking for a related subject,
    your website came up, it seems great. I’ve bookmarked it in my google bookmarks.

    Hello there, simply become alert to your blog thru
    Google, and located that it is truly informative.
    I am going to watch out for brussels. I will be grateful for those who continue
    this in future. Many people will likely be benefited out of your writing.
    Cheers!

  13. Stephenideox表示:

    Бесплатный информационный сервис, предоставляющий контент и справочную информацию о инвестировании.
    правительство инвестиции

  14. Winnie Henry表示:

    The roof market has changed a lot over the last few years with brand-new products and technologies. I wonder about the most recent patterns roofing company in tampa

  15. іd=”firstHeading” class=”firstHeading mw-first-heading”>Search гesults

    Heⅼⲣ

    English

    Tools

    Tools
    mⲟve tߋ sidebbar hide

    Actions

    General

    Herе is my website – ดอกไม้แสดงความยินดี

  16. DarrenUnjuh表示:

    http://plavixclo.com/# Plavix generic price

發佈留言

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