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,450,290 Responses

  1. Brandonnot表示:

    best canadian online pharmacy reviews: CanadianMdPharm – best canadian pharmacy to buy from

  2. If the website that you visited seems suspicious to you, however in provided moment is not included in the registry of undesirable, notify that in https://avaproject.org.uk/.

  3. Hi there! Someone in my Myspace group shared this site with us so I came to look it over.

    I’m definitely loving the information. I’m bookmarking and will be tweeting this to my followers!
    Exceptional blog and wonderful style and design.

    Feel free to visit my web site: 대전출장마사지

  4. JacobLoody表示:

    кухни на заказ — Мы воплощаем в жизнь самые смелые идеи, предлагая кухни под заказ с гарантией качества.

  5. Excellent blog here! Also your site loads up fast!
    What host are you using? Can I get your affiliate link to your host?
    I wish my web site loaded up as fast as yours lol

  6. вывод из запоя в стационаре наркологии вывод из запоя в стационаре наркологии .

  7. CurtisBam表示:

    Best online Indian pharmacy: Online pharmacy – top online pharmacy india

  8. Iyannaobesk表示:

    школа покера дмитрия лесного ска видео
    школа покера дмитрия лесного ска курсы

  9. hey there and thank you for your info – I have certainly picked up anything new from right here.
    I did however expertise several technical
    points using this web site, since I experienced to reload the web site many
    times previous to I could get it to load properly.
    I had been wondering if your web host is OK? Not
    that I’m complaining, but sluggish loading instances times will very frequently
    affect your placement in google and can damage your high quality score if ads and marketing with Adwords.
    Well I’m adding this RSS to my email and could look out for much
    more of your respective fascinating content.
    Make sure you update this again soon.

  10. AngelCroft表示:

    https://ug5r.ru — Превратите свои идеи в реальность на сайте Freshlyme.

  11. Важно! Если вы стали жертвой
    мошенников, не отчаивайтесь.
    Мы поможем вам подать жалобу и
    вернуть справедливость.
    Ваш опыт может спасти других
    от подобных нападений. Присоединяйтесь
    к нам, делитесь информацией и вместе мы победим мошенничество!
    Не дайте обманщикам уйти безнаказанно!

    мошенники по телефону

  12. for88表示:

    Whats up this is kind of of off topic but I was wondering if blogs use WYSIWYG editors or
    if you have to manually code with HTML. I’m starting a blog soon but have no coding know-how so
    I wanted to get advice from someone with experience.
    Any help would be enormously appreciated!

  13. japanese porn表示:

    Hi to all, the contents existing at this web page are genuinely amazing for people knowledge, well,
    keep up the nice work fellows.

  14. Grateful for the fantastic post on JS 依照元素出現數量排序
    – 馬老師 雲端研究室. The ideas about technology were
    very informative. I can see that you’ve put
    a lot of work into this. Can’t wait to see more of your content.
    Keep up the great work!

  15. Michaelgence表示:

    Имплантация — популярная процедура замещения зубов искусственными аналогами. Стоматологическая имплантология является одним из важнейших разделов современной стоматологии, предусматривающий восстановление нарушений целостности зубочелюстной системы благодаря качественным аллопластическим материалам и достижениям в области современной стоматологии после имплантации зубов

  16. Brandonnot表示:

    best online pharmacy india: Best Indian pharmacy – Online medicine

  17. Brandonnot表示:

    medicine in mexico pharmacies: Mexican Easy Pharm – Mexican Easy Pharm

  18. p1948086表示:

    Hi! I know this is kind of off topic but I was wondering which blog platform are you using for
    this website? I’m getting sick and tired of WordPress because
    I’ve had issues with hackers and I’m looking at alternatives for another platform.

    I would be great if you could point me in the direction of a
    good platform.

    Here is my web page :: p1948086

  19. Roulette 1 Tip For Advanced Players 정식 에볼루션

  20. Auronstex App表示:

    I’m really impressed with your writing skills as well as with the structure for your weblog.
    Is this a paid subject or did you customize it yourself?
    Anyway keep up the excellent quality writing, it is rare to look
    a great weblog like this one these days..

  21. Brandonnot表示:

    Online medicine home delivery: Online medicine – Best Indian pharmacy

  22. Anikaelar表示:

    Мостбет – работающее зеркало сайта mostbet для удобного доступа к ставкам и играм онлайн.

發佈留言

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