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,477,968 Responses

  1. buket_dcma表示:

    Как выбрать идеальный букет невесты, для незабываемого образа на свадьбе.
    DIY букет невесты: легкий и креативный способ, для особенного момента.
    Лучшие тренды в букете невесты, для свадебной церемонии.
    Бюджетный вариант букета невесты: красиво и доступно, который порадует вас и вашего жениха.
    Свежие цветы или нет: какой букет невесты лучше, чтобы было меньше забот и больше радости.
    Букет невесты в стиле минимализм, для свадьбы в скандинавском стиле.
    Как выбрать букет невесты, который идеально подойдет к свадебному наряду, для выразительных свадебных образов.
    букет невесты нн букет невесты нн .

  2. Website表示:

    Hi, I do think this is an excellent web site. I stumbledupon it 😉 I may revisit yet again since i have book marked
    it. Money and freedom is the greatest way to change, may you be rich and continue
    to help other people.

  3. DarioTob表示:

    вавада онлайн казино: vavada kazi – казино вавада

  4. CurtisIncix表示:

    vavada: vavada-kazi.ru – vavada-kazi.ru

  5. What’s The Most Creative Thing That Are Happening With Best Butt Plug vibrating buttplug for men – younghwacarbon.com,

  6. Mursorbit App表示:

    Excellent blog here! Also your website loads up fast!
    What web host are you the usage of? Can I
    get your associate link on your host? I want my web site loaded up as fast as yours lol

  7. Hello There. I found your blog using msn. This is a very well written article.

    I will make sure to bookmark it and return to read more of your useful info.
    Thanks for the post. I’ll certainly return.

  8. check that表示:

    I know this site presents quality based posts and extra material, is there any other site which presents such data in quality?

  9. Pol88表示:

    When I originally commented I clicked the “Notify me when new comments are added”
    checkbox and now each time a comment is added I get several e-mails with the
    same comment. Is there any way you can remove people from that service?

    Thank you!

  10. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали сервисный центр philips, можете посмотреть на сайте: сервисный центр philips
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  11. Excellent way of telling, and nice post to obtain facts concerning my presentation focus,
    which i am going to present in university.

  12. Davao表示:

    Live Casino Games Davao

  13. I like the valuable info you supply for your articles.
    I will bookmark your weblog and take a look at once more right here frequently.
    I’m reasonably certain I will be informed plenty of new stuff right here!

    Good luck for the following!

  14. bookmarked!!, I like your web site!

  15. DarioTob表示:

    pinup kazi: пин ап казино – пинап казино

  16. Post writing is also a fun, if you be acquainted with then you can write otherwise it
    is difficult to write.

  17. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали официальный сервисный центр huawei, можете посмотреть на сайте: официальный сервисный центр huawei
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  18. Hey I know this is off topic but I was wondering if you knew of
    any widgets I could add to my blog that automatically tweet my newest twitter updates.
    I’ve been looking for a plug-in like this for quite some time
    and was hoping maybe you would have some experience with something like this.
    Please let me know if you run into anything. I truly enjoy reading your blog and I look forward
    to your new updates.

  19. Jamesdiure表示:

    пин ап казино: пин ап казино онлайн – pin up казино

  20. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали сервисный центр philips в москве, можете посмотреть на сайте: сервисный центр philips в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  21. Josephmax表示:

    http://pinup-kazi.ru/# пин ап казино

  22. CurtisIncix表示:

    казино вавада: вавада онлайн казино – vavada-kazi.ru

  23. I have been surfing on-line more than three hours today, yet
    I never discovered any attention-grabbing article like yours.

    It is lovely price enough for me. In my opinion, if all web owners and bloggers made just right content
    as you did, the web can be a lot more helpful than ever before.

  24. I’m extremely impressed with your writing skills as well as with the layout on your blog.

    Is this a paid theme or did you modify it yourself?
    Either way keep up the excellent quality writing, it’s rare to see a great blog like this one today.

    my web page – best realtor in Meridian Ms

發佈留言

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