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,629,631 Responses

  1. Five Killer Quora Answers On SEO Company Glasgow seo company glasgow

  2. certainly like your website but you need to take a look at the spelling on several
    of your posts. Many of them are rife with spelling issues and I find it very troublesome to
    inform the reality on the other hand I’ll definitely come back again.

  3. Williamagric表示:

    best erection pills http://mexicanpharm24.cheap/# purple pharmacy mexico price list

  4. LeroyBak表示:

    erectile dysfunction treatment buy drugs ed treatment options

  5. Williamagric表示:

    cheapest ed pills https://indianpharm24.pro/# indianpharmacy com

  6. Thank you for the auspicious writeup. It in fact was a amusement account
    it. Look advanced to far added agreeable from you!
    By the way, how could we communicate?

  7. Jorgeagopy表示:

    indianpharmacy com: Pharmacies in India that ship to USA – indian pharmacy

  8. DevonPhack表示:

    http://indianpharm24.pro/# top 10 pharmacies in india
    how can i order prescription drugs without a doctor

  9. i ready表示:

    Hey there! I know this is somewhat off topic but I was wondering which blog platform are you using for this site?

    I’m getting fed up of WordPress because I’ve had problems 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.

  10. Jamesses表示:

    Познакомьтесь с нашим профессиональным коллективом, который созидает уникальную мебель, воплощая ваши мечты в течение реальность https://www.cehitae2kuhnishki.ru.

  11. Jorgeagopy表示:

    ed vacuum pumps: buy drugs – medications online

  12. BrandonSaisy表示:

    canadian drugstore online: cheap meds – ed drugs

  13. Wow, wonderful blog layout! How long have you been blogging
    for? you made blogging look easy. The overall look
    of your website is fantastic, as well as the content!

  14. It’s The Good And Bad About Penis Machine For Women sex Machine on sale

  15. DevonPhack表示:

    http://indianpharm24.pro/# world pharmacy india
    how to treat ed

  16. slot表示:

    bookmarked!!, I love your site!

  17. slot表示:

    Awesome! Its in fact amazing piece of writing, I have got much clear idea concerning from this article.

  18. Pomodoro is the Italian word for tomato so any dish with this word means it has tomatoes mixed in there.

  19. Jorgeagopy表示:

    buying from online mexican pharmacy: mexico pharmacy – mexican mail order pharmacies

  20. Jorgeagopy表示:

    cheap medications online: cheap medication – buy ed drugs online

  21. Williamagric表示:

    prescription drugs without doctor approval https://indianpharm24.pro/# india pharmacy

  22. You’ll Be Unable To Guess Situs Togel Dan Slot Terpercaya’s Tricks situs
    togel dan slot terpercaya (https://www.google.Com.pe)

  23. eksport oleju表示:

    Heya i am for the first time here. I found this board and I find It really useful & it helped
    me out much. I hope to give something back and help others like you
    helped me.

  24. Helpful information. Fortunate me I discovered your site accidentally, and I’m surprised why
    this accident didn’t took place in advance!

    I bookmarked it.

  25. sd247.biz表示:

    Hello excellent website! Does running a blog
    like this require a large amount of work? I’ve absolutely no understanding of
    computer programming however I had been hoping to start my own blog in the near future.
    Anyway, should you have any ideas or techniques for new blog owners please share.
    I know this is off topic but I simply wanted to ask.
    Appreciate it!

  26. Lazrvue表示:

    Официальное получение диплома техникума с упрощенным обучением в Москве

    rashin.4adm.ru/viewtopic.php?f=27&t=2393

  27. situs 4d表示:

    Guide To Situs 4d: The Intermediate Guide To Situs 4d situs 4d

  28. Lazrvtk表示:

    Стоимость дипломов высшего и среднего образования и процесс их получения

    shooting-russia.ru/forum/?PAGE_NAME=message&FID=5&TID=16552&TITLE_SEO=16552-ofitsialnyy-diplom-za-neskolko-dney-_-vashe-budushchee-nachinaetsya-seychas&MID=16828&result=new#message16828

  29. DevonPhack表示:

    http://indianpharm24.pro/# mail order pharmacy india
    homeopathic remedies for ed

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

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