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,244,729 Responses

  1. Markdob表示:

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

  2. BrandenSlomy表示:

    prednisone uk price: prednisone ray pharm – best pharmacy prednisone

  3. What’s up colleagues, how is everything, and what you want to say about this
    paragraph, in my view its truly awesome for me.

  4. Markdob表示:

    Всем привет! Может кто знает, где почитатьполезные статьи о недвижимости? Сейчас читаю – https://dar-dereva.ru

  5. After I initially left a comment I appear to have clicked on the -Notify me when new comments are added- checkbox and from now
    on whenever a comment is added I get four emails with the
    same comment. Is there an easy method you can remove me
    from that service? Thanks!

  6. Hi, I do believe this is an excellent blog. I stumbledupon it 😉
    I’m going to come back once again since I book marked it.
    Money and freedom is the greatest way to change,
    may you be rich and continue to help others.

  7. Markdob表示:

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

  8. Medication information sheet. What side effects can this medication cause?
    can i purchase azelastine tablets
    All what you want to know about medication. Get here.

  9. yui tatsumi表示:

    Greetings from Idaho! I’m bored to tears at work so I
    decided to check out your site on my iphone during lunch
    break. I love the information you provide here and can’t wait
    to take a look when I get home. I’m amazed at how quick your blog loaded on my mobile ..

    I’m not even using WIFI, just 3G .. Anyways, good
    site!

  10. Stephenphync表示:

    Когда я впервые открыл этот сайт, впечатление было таким, будто я нашёл что-то особенное. Здесь каждая ставка — это не просто азарт, а эмоция, которую ты ощущаешь с каждым кликом.

    Оформление интуитивен, словно легкое прикосновение направляет тебя от игры к игре. Финансовые движения, будь то депозиты или вывод средств, проходят легко, как поток воды, и это вдохновляет. А техподдержка всегда готова подхватить, как друг, который никогда не оставит.

    Для меня azino 777 стал местом, где азарт и искусство сплетаются. Здесь каждая минута — это часть картины, которую хочется переживать снова и снова.

  11. StevenNub表示:

    clomid without prescription: generic clomid – where can i get cheap clomid

  12. ElbangBit App表示:

    I’m amazed, I must say. Rarely do I come across a blog that’s both educative and interesting, and let me
    tell you, you’ve hit the nail on the head. The problem is something that
    too few men and women are speaking intelligently about.
    Now i’m very happy I came across this during my search for something relating to
    this.

  13. These are truly fantastic ideas in on the topic of blogging.
    You have touched some pleasant things here. Any way keep up wrinting.

  14. StevenNub表示:

    clomid buy: rex pharm – cost generic clomid without insurance

  15. StevenNub表示:

    amoxicillin order online no prescription: Amoxicillin for sale – amoxicillin 500 capsule

  16. wps表示:

    I do not know if it’s just me or if everyone else encountering problems with your website.

    It seems like some of the text within your content are running off
    the screen. Can somebody else please comment and let me know if this is happening to them too?

    This could be a problem with my web browser because
    I’ve had this happen previously. Many thanks

  17. BrandenSlomy表示:

    prednisone 20mg price: ray pharm – prednisone 10 mg over the counter

  18. Saved as a favorite, I love your blog!

    Feel free to visit my blog :: Pinoy SEO Services Philippines

  19. That is really interesting, You’re a very professional blogger.
    I have joined your feed and stay up for searching for more of your magnificent
    post. Additionally, I have shared your site in my social networks

  20. Dereketerm表示:

    prednisone cost canada: prednisone – prednisone buy cheap

  21. Dannyunoto表示:

    Сопровождение мужчин — это особая услуга, которая может включать в себя как деловые, так и личные аспекты.
    В современном мире многие мужчины ищут профессионалов, которые могут помочь им в различных сферах жизни:
    от бизнес-мероприятий до социальных встреч – девушки в Москве на час

  22. ICONWIN表示:

    I have been browsing on-line greater than three hours today, but I never found any
    attention-grabbing article like yours. It is pretty value sufficient for me.
    In my view, if all web owners and bloggers made excellent content as
    you probably did, the web will likely be a lot more useful than ever before.

發佈留言

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