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,266,078 Responses

  1. SmdPaish表示:

    Figure out the best treatment pricing for prescriptions of what are the side effects of keflex misconceptions about online ordering. Don’t be ignorant, read

  2. topcartuning表示:

    I do agree with all the concepts you have introduced
    in your post. They’re really convincing and can certainly work.
    Still, the posts are very quick for starters. Could you please extend them a
    bit from subsequent time? Thanks for the post.

  3. Полезная информация о применении индустриальных масел, Лучшие виды индустриальных масел, Советы по выбору индустриальных масел, чтобы оптимизировать работу оборудования, для успешного развития производства, Индустриальные масла: лучшие практики использования, Экологическая ответственность в выборе масел, для соблюдения экологических стандартов, для повышения производительности предприятия, для оптимизации бюджета
    веретенное масло и 20 веретенное масло и 20 .

  4. DarioTob表示:

    pinup-kazi.ru: пинап казино – pinup-kazi.ru

  5. Jamesdiure表示:

    pinup: pinup – пинап казино

  6. Donte Grasby表示:

    Introduction: The ketogenic diet has gained immense popularity in recent years due to its ability to induce weight loss and improve overall health. However, adhering to a keto diet can be challenging, especially for individuals with busy lifestyles.

  7. Ralph Dean表示:

    This was a great article. Check out Industrial Welding Inspection of Mesa for more

  8. How To Make An Amazing Instagram Video About Cast Aluminium Chiminea
    Cast Aluminum chiminea

  9. Josephmax表示:

    http://pinup-kazi.kz/# pinup-kazi.kz

  10. Jamesdiure表示:

    pinup-kazi.kz: пин ап кз – пинап казино

  11. I’m curious to find out what blog platform you’re working with?
    I’m experiencing some minor security problems
    with my latest blog and I would like to find something more
    risk-free. Do you have any recommendations?

    My website real estate agent in columbus oh

  12. Josephmax表示:

    http://pinup-kazi.kz/# pinup kazi

  13. Iyannaobesk表示:

    1win покер реальные отзывы
    1win покер отзывы игроков

  14. Josephmax表示:

    http://pinup-kazi.kz/# пинап казино

  15. I’m truly enjoying the design and layout of your site.

    It’s a very easy on the eyes which makes it much more enjoyable for me to
    come here and visit more often. Did you hire out a developer to create your theme?
    Outstanding work!

  16. 알밤表示:

    Late Night Fun 알밤

  17. Spot on with this write-up, I honestly believe this site needs
    far more attention. I’ll probably be back again to read
    more, thanks for the information!

    my webpage; best realtor in columbus oh

  18. Meds information. What side effects?
    cost of generic minocycline without prescription
    Actual news about drug. Read information now.

  19. HenrydeT表示:

    pin up казино pin up казино pinup

  20. HenrydeT表示:

    вавада онлайн казино вавада казино зеркало вавада казино зеркало

  21. HenrydeT表示:

    вавада казино онлайн вавада казино онлайн вавада казино онлайн

  22. HenrydeT表示:

    пин ап кз pinup kazi pinup kazi

發佈留言

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