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,480,032 Responses

  1. Hello There. I found your blog using msn. This is a really well written article.
    I’ll make sure to bookmark it and return to read more of
    your useful info. Thanks for the post. I’ll definitely
    comeback.

  2. Hello, I think your blog might be having browser compatibility issues.
    When I look at your website in Chrome, it looks fine but when opening in Internet Explorer, it has some
    overlapping. I just wanted to give you a quick
    heads up! Other then that, terrific blog!

  3. Nikefut表示:

    deep web drug url darkmarkets tor marketplace

  4. Very good article. I’m going through some of
    these issues as well..

  5. This is an effort to de-sulfate the Best YouTube tutorials for refurbishing golf cart batteries –
    https://upi.ind.in/blog/index.php?entryid=17185, and
    must enhance the variety and capability once again.

  6. BernardMop表示:

    buy Lisinopril online buy Lisinopril 1st cheapest Lisinopril

  7. Hi! I know this is kinda off topic but I was wondering which blog
    platform are you using for this site? I’m getting sick and tired of WordPress because I’ve
    had issues with hackers and I’m looking
    at options for another platform. I would be great if you could point me in the direction of a good platform.

  8. Hello! I know this is kinda 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!

  9. I’m really enjoying the theme/design of your website.
    Do you ever run into any internet browser compatibility
    problems? A number of my blog readers have complained about my blog not operating correctly in Explorer but looks great in Opera.
    Do you have any recommendations to help fix this issue?

  10. Hello there, You’ve done a great job. I will definitely digg it and personally suggest to my friends.

    I am confident they’ll be benefited from this site.

  11. Building a manufacturer on-line requires know-how, and a superb electronic advertising and marketing employer can make your complete difference Digital Marketing

  12. Rosa Wilkins表示:

    This write-up completely highlights the importance of mobile optimization in SEO advertising and marketing. With so many individuals on smart phones, it’s a must! For additional understandings, don’t forget to check out search engine optimization pricing

  13. BrandenSlomy表示:

    buy priligy: buy priligy – max pharm

  14. Markdob表示:

    Приветствую. Подскажите, где найтиразные блоги о недвижимости? Пока нашел – https://texnotect.ru

  15. Markdob表示:

    Всем привет! Может кто знает, где почитатьполезные блоги о недвижимости? Пока нашел – https://texnotect.ru

  16. BernardMop表示:

    cheapest Lisinopril buy Lisinopril 1st buy Lisinopril 1st

  17. TerryUtine表示:

    На данный момент антигравийная пленка считается материалом, который отлично защищает кузов авто от различных повреждений. Так, она поможет избежать царапин, потертостей, а также предохраняет машину во время небольших ДТП, и в результате на поверхности авто не появляется ржавчина https://blogs.rufox.ru/~runoklisfgy/51744.htm

  18. BrandenSlomy表示:

    prednisone price canada: raypharm – prednisone cream

  19. Good way of describing, and nice article to obtain information regarding my presentation topic, which i
    am going to present in university.

  20. Markdob表示:

    Приветствую. Может кто знает, где почитатьразные статьи о недвижимости? Сейчас читаю – https://texnotect.ru

  21. Nikefut表示:

    bitcoin dark web darknet drugs dark websites

  22. DarrenUnjuh表示:

    https://plavixclo.com/# п»їplavix generic

  23. Markdob表示:

    Приветствую. Подскажите, где почитатьполезные статьи о недвижимости? Сейчас читаю – https://texnotect.ru

  24. op表示:

    Burlesque Show op

  25. DarrenUnjuh表示:

    http://iverfast.com/# ivermectin 4000 mcg

發佈留言

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