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,248,958 Responses

  1. ラブドール 中古During testing the owners were instructed to say a word corresponding to an object before showing the dog either the correct item or one that did not fit the label.An owner might say,

  2. ‘klcc magnificent penthouse

  3. Hello, i think that i saw you visited my website so i came
    to “return the favor”.I’m attempting to find things to enhance
    my web site!I suppose its ok to use some of your ideas!!

  4. DarrenUnjuh表示:

    https://lisinopril1st.com/# lisinopril1st

  5. 789win表示:

    bookmarked!!, I love your blog!

  6. I am not sure where you’re getting your information, but great topic.
    I needs to spend some time learning more or understanding more.
    Thanks for excellent information I was looking for this info for my mission.

  7. BrandenSlomy表示:

    50 mg prednisone canada pharmacy: prednisone ray pharm – buy prednisone 1 mg mexico

  8. DustinTon表示:

    Эвакуатор с манипулятором – универсальное решение для перевозки автомобилей. Он сочетает функции обычного эвакуатора и крана-манипулятора. Это позволяет решать сложные задачи по эвакуации. Манипулятор может поднимать и перемещать грузы в труднодоступных местах https://kak-cdelat.ru/inventar/210-detskaya-shvedskaya-stenka-svoimi-rukami-chertezhi.html

  9. agriculture land for sale selangor

  10. price is just one of the factor to buy penthouse

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

  12. Violet Hines表示:

    Excellent article on roof inspections! Regular checks can save homeowners a lot of money. For more tips on maintaining your roof, head over to roofing Contractor

  13. Pol88表示:

    Hey there! I’ve been reading your weblog for a long time now and finally
    got the courage to go ahead and give you a shout out from
    Humble Tx! Just wanted to say keep up the good job!

  14. BrandenSlomy表示:

    can i buy clomid without rx: clomid online – where buy generic clomid tablets

  15. AlbertDuM表示:

    buy cytotec over the counter: cytpremium – buy cytotec

  16. buying land in florida

  17. I’ll immediately grab your rss feed as I can not
    find your e-mail subscription hyperlink or newsletter
    service. Do you’ve any? Kindly allow me know in order that I may subscribe.
    Thanks.

  18. AlbertDuM表示:

    Lisinopril 1st: cheapest Lisinopril – buy Lisinopril 1st

  19. prefer luxury only penthouse in klcc

  20. очерк об Cryptoboss casino, которое уникально тем что
    принимает в оплату все криптовалюты мира

  21. What’s up i am kavin, its my first occasion to commenting anywhere, when i read this
    piece of writing i thought i could also make comment due
    to this brilliant article.

  22. Fantastic post but I was wanting to know if you could write a litte more on this subject?
    I’d be very thankful if you could elaborate a little bit further.
    Appreciate it!

    Feel free to visit my page dementia housing

發佈留言

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