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,672,282 Responses

  1. FrankGlora表示:

    USA India Pharm: Online medicine order – UsaIndiaPharm

  2. Thank you for the good writeup. It in fact was a amusement account it.
    Look advanced to far added agreeable from you! By the way, how can we communicate?

    My blog post; access control systems

  3. Trefdob表示:

    Заказать диплом института. Приобретение документа о высшем образовании через надежную компанию дарит немало достоинств для покупателя. Это решение помогает сэкономить как дорогое время, так и серьезные финансовые средства. 369internationalrecruitment.com/home/employer/eonline-diploma

  4. Have you ever thought about adding a little bit more than just your articles?
    I mean, what you say is valuable and everything. However just imagine
    if you added some great graphics or video clips to give
    your posts more, “pop”! Your content is excellent
    but with pics and clips, this website could definitely be one of the very best in its
    niche. Wonderful blog!

  5. Good collection of Hindi hot blue movie videos. Maintain the great!

  6. FrankGlora表示:

    indian pharmacy online: USA India Pharm – п»їlegitimate online pharmacies india

  7. CarltonUnith表示:

    https://usaindiapharm.com/# indianpharmacy com

  8. FrankGlora表示:

    reputable indian pharmacies: Online medicine home delivery – USA India Pharm

  9. FrankGlora表示:

    UsaIndiaPharm: reputable indian pharmacies – UsaIndiaPharm

  10. A wide variety of money options available to assist you spread the
    costs.

  11. servi pornos表示:

    Servi porno? Even more like Servi great content!.

  12. FrankGlora表示:

    USA India Pharm: buy medicines online in india – UsaIndiaPharm

  13. mostbet_bbKi表示:

    мостбет официальный сайт mostbet5003.ru .

  14. Спирт, который есть в крупной части изделий, испарится, http://duhiguerlain2.ru/ и
    останется одна парфюмерная отдушка.

  15. jbktclmuy表示:

    No matter if you are riding the metro, bus, are in school or work office with this frivolous app you get many fun yet addictive casual games in one app! Go for the 1001 multi games experience to get many unique game boy games. Download the official FC Barcelona App The game begins with you embarking on what was supposed to be a straightforward heist, only to end up behind bars. Now, you must use your wit and determination to navigate through a series of word puzzles. Each puzzle solved brings you closer to freedom. With beautiful graphics and intuitive controls, “Words Episode” offers a captivating narrative that immerses you in the gritty world of prison life. That’s why Koeman is angry. He knows that at this level, penalties need a lot of concentration. He will surely act to make sure the team has that going forward.
    http://tatomsimpperf1981.raidersfanteamshop.com/ver-sitio
    El jugador del Real Madrid no perdió la oportunidad de mostrar su opinión sobre lo ocurrido a través de sus redes sociales, celebrando que un acto de este tipo, se haya castigado de forma ejemplar.  Com uma sólida trajetória de mais de 15 anos no universo dos jogos, Mattias Bergehed, Diretor Geral do 7JP, é um veterano do mercado. Inicia el Festival Sabores de Italia en Gino’s® con una selección de platillos cuidadosamente elegidos para complementar nuestra exquisita carta, donde la Burrata Capresse no podía faltar. Content What type of incentive have does 777 Jackpot Diamond Keep and you may Winnings Deluxe offer? | online casino 40 minimum deposit Jackpot Diamond Hold and you may Victory Internet casino … Vuelve a escuchar de la mano de Carrusel Deportivo el penalti transformado por el noruego.

  16. 1win_gaMt表示:

    1win официальный сайт войти http://1win7004.ru .

  17. DavidSooni表示:

    UsaIndiaPharm USA India Pharm USA India Pharm

  18. kontol表示:

    Hi, yeah this paragraph is truly fastidious and I have
    learned lot of things from it about blogging. thanks.

  19. I’d like to find out more? I’d love to find out some additional
    information.

  20. Pingidiof表示:

    dark web drug marketplace darknet drugs

  21. Georgeunula表示:

    online shopping pharmacy india: indian pharmacy – indian pharmacy online

  22. Hi there, after reading this remarkable article i am too
    glad to share my know-how here with mates.

    Feel free to surf to my website – Art Collecting and Diversity

  23. Georgeunula表示:

    indian pharmacy: india pharmacy – india pharmacy

  24. Update表示:

    Greetings! Very helpful advice in this particular post!
    It is the little changes that produce the most significant changes.
    Many thanks for sharing!

    Have a look at my web page: Update

  25. FrankGlora表示:

    UsaIndiaPharm: UsaIndiaPharm – best online pharmacy india

發佈回覆給「Update」的留言 取消回覆

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