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,249,542 Responses

  1. DarrenUnjuh表示:

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

  2. You’ve made some good points there. I checked on the internet to find out more about the issue
    and found most individuals will go along with your views on this web site.

    my homepage: 메리트카지노후속

  3. JacobLoody表示:

    кухня под заказ — Индивидуальный подход к созданию вашей идеальной кухни.

  4. AlbertDuM表示:

    buy plavix: cheapest plavix – buy Clopidogrel over the counter

  5. whoah this weblog is fantastic i love reading your articles.
    Keep up the good work! You know, lots of individuals are hunting round for
    this info, you can aid them greatly.

  6. BrandenSlomy表示:

    can we buy amoxcillin 500mg on ebay without prescription: cheap amoxil – amoxicillin 500 mg tablet

  7. I have been surfing online greater than three hours these days, but I bby no means found any attention-grabbing article like yours.
    It is lovely value sufficient for me. Personally, if all site ownewrs and bloggers
    made good content as you probably did, the net will probably be a lot more helpful thhan ever before.

    My homepage … liga eropa hari ini

  8. DarrenUnjuh表示:

    http://lisinopril1st.com/# buy Lisinopril online

  9. Использование костной муки на блокировку мангровых листьев с блоком воздуха под агрегатом приводит к появлению висячего мангрового.

    Feel free to surf to my web-site :: https://khabmama.ru/forum/viewtopic.php?t=255203

  10. most sort after penthouse with unblock klcc view

  11. BrandenSlomy表示:

    amoxicillin 50 mg tablets: amoxil – how to buy amoxicillin online

  12. I visited many blogs however the audio feature for audio songs present at this site is truly fabulous.

    Also visit my blog; independent living communities

  13. AlbertDuM表示:

    ivermectin brand: minocycline 100mg over the counter – stromectol how much it cost

  14. DarrenUnjuh表示:

    https://iverfast.com/# stromectol ivermectin

  15. AlbertDuM表示:

    buy Lisinopril 1st: Lisinopril 1st – buy Lisinopril 1st

  16. DarrenUnjuh表示:

    http://lisinopril1st.com/# buy Lisinopril online

  17. penthouse without pool consider standard penthouse

  18. DustinTon表示:

    Эвакуатор с манипулятором – универсальное решение для перевозки автомобилей. Он сочетает функции обычного эвакуатора и крана-манипулятора. Это позволяет решать сложные задачи по эвакуации. Манипулятор может поднимать и перемещать грузы в труднодоступных местах http://ani-dub.ru/genre/mexa

  19. id=”firstHeading” class=”firstHeading mw-first-heading”>Search reѕults

    Ꮋelp

    English

    Tools

    Tools
    m᧐ᴠe too sidebar hidse

    Actions

    Ԍeneral

    my һomepage: ดอกไม้หน้าโลง ใกล้ฉัน

發佈留言

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