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,684,240 Responses

  1. slot5000表示:

    Asking questions are in fact pleasant thing if you are not
    understanding anything fully, however this post presents fastidious understanding
    even.

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

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

    Мы гарантируем полную конфиденциальность и соблюдение
    всех этических норм.
    Если вы столкнулись с
    уголовным делом, не стесняйтесь обращаться к нам за помощью.

    Мы всегда готовы помочь и защитить ваши права и свободы.

  3. Faith表示:

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

  4. Hmm is anyone else having problems with the pictures on this blog loading?
    I’m trying to find out if its a problem on my end or if it’s the blog.

    Any suggestions would be greatly appreciated.

  5. Ruben Ball表示:

    https://seo10.z11.web.core.windows.net/research/seo10-(154).html
    If you want your legs, you may need to go along with an above-the-knee or just-below-the-knee gown.

  6. What’s up, after reading this remarkable piece of writing i am too cheerful to share my experience here with friends.

  7. I really like what you guys are up too. This sort of clever work and coverage!

    Keep up the great works guys I’ve added you guys to
    my own blogroll.

  8. Good – I should definitely pronounce, impressed with your website. I had no trouble navigating through all tabs and related information ended up being truly simple to do to access. I recently found what I hoped for before you know it at all. Reasonably unusual. Is likely to appreciate it for those who add forums or anything, site theme . a tones way for your customer to communicate. Nice task.

    my website: https://dribbble.com/bidathinhkent

  9. Keep functioning ,terrific job!

    My web-site: various billiarballs (https://www.exchangle.com/bidathinhkent)

  10. Zulma Mistry表示:

    Fantastic forum posts, Thanks!

  11. King Cardin表示:

    Thanks! Lots of facts.

  12. Very quickly this web page will be famous among
    all blogging viewers, due to it’s fastidious
    articles

  13. Health表示:

    %%

    Here is my page; Health

  14. airport taxis表示:

    It’s nearly impossible to find well-informed people for this topic,
    however, you seem like you know what you’re talking about!
    Thanks

  15. Vania表示:

    %%

    Also visit my webpage; local electrician flitwick; Vania,

  16. Brenda表示:

    You actually make it seem so easy together with your presentation but I to find this topic to be
    actually one thing that I believe I might by no means understand.
    It seems too complex and extremely broad for me. I’m taking a look forward for your subsequent
    post, I will try to get the grasp of it!

  17. หนังX表示:

    Howdy! I realize this is somewhat off-topic however I needed to ask.
    Does managing a well-established blog such as yours take a massive amount work?
    I am completely new to writing a blog but I do write in my diary
    daily. I’d like to start a blog so I can easily share my experience and feelings online.
    Please let me know if you have any ideas or tips for brand new aspiring blog owners.
    Appreciate it!

  18. %%

    My web site; psychiatrist London (http://www.ghiblies.net)

  19. Because the admin of this web site is working, no question very soon it will be renowned, due to its feature contents.

  20. %%

    Feel free to surf to my page :: premium full spectrum

  21. Hi there! I know this is kind of off topic but I was wondering if you knew where I could get a
    captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having difficulty finding
    one? Thanks a lot!

  22. levis4d表示:

    Pretty! This was an extremely wonderful post.
    Many thanks for providing these details.

發佈回覆給「Vicente Lester」的留言 取消回覆

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