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,479,508 Responses

  1. BrandenSlomy表示:

    prednisone best prices: prednisone – canada buy prednisone online

  2. Annie Pratt表示:

    I always thought roofing was basic till I attempted it myself! It’s absolutely best delegated the pros. If you’re uncertain who to work with, I recommend visiting roof repairs in tampa for recommendations on qualified roofers in your location

  3. AlbertDuM表示:

    Plavix generic price: buy Plavix Clo – buy clopidogrel online

  4. DarrenUnjuh表示:

    http://iverfast.com/# buy stromectol canada

  5. BrandenSlomy表示:

    cheap priligy: dapoxetine online – priligy maxpharm

  6. Nikefut表示:

    tor markets links darknet sites darknet search engine

  7. I think this is among the so much important information for me.

    And i am satisfied studying your article. However want to statement on few general things, The site taste is ideal, the articles is in reality nice :
    D. Excellent activity, cheers

  8. Pacman168vip表示:

    Pacman168vipยกขบวนเกมสล็อตยอดฮิตจากค่ายดังต่างประเทศ

  9. Appreciate the recommendation. Let me try it out.

  10. If you are going for best contents like I do, simply go to
    see this web site everyday since it provides feature contents, thanks

  11. Randy Walton表示:

    Tôi rất thích cách hitClub tổ chức các sự kiện thú vị cho người chơi hit club đăng nhập

  12. Your means of telling the whole thing in this piece of writing
    is actually fastidious, every one be capable of easily
    know it, Thanks a lot https://www.provenexpert.com/de-de/pub021/

  13. This Is The History Of Adultsextoys In 10 Milestones toys for men adult

  14. Nice post. I learn something new and challenging on websites I
    stumbleupon on a daily basis. It will always be useful to read through articles from other
    authors and practice a little something from
    their sites.

  15. 5 Laws Anyone Working In Car Key Cut Should Be Aware Of Who Cuts Car Keys Near Me

  16. Drug information leaflet. Effects of Drug Abuse.
    where can i buy cheap pioglitazone
    Everything trends of drugs. Read information here.

  17. TerryUtine表示:

    На данный момент антигравийная пленка считается материалом, который отлично защищает кузов авто от различных повреждений. Так, она поможет избежать царапин, потертостей, а также предохраняет машину во время небольших ДТП, и в результате на поверхности авто не появляется ржавчина https://yo-mi.ru/people/user/4229/blog/1857/

  18. The importance of proper ventilation in roofing cannot be overstated! Thanks for highlighting that. For more info on roofing ventilation, visit Roofer

  19. Nikefut表示:

    dark web drug marketplace deep dark web darknet market links

發佈留言

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