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,246,999 Responses

  1. Voce teve um sonho incomum?
    Olhar num espelho num sonho

    [url=http://milkywaygalaxynews.com/about/comment-page-12/#comment-7650669]Porque e que sonho com o kvass?[/url] [url=http://www.vimalakirti.com/tc/yybbs/yybbs.cgi?list=thread]Sonho de um gato adormecido[/url] [url=http://www.0909j.com/mb/prinet/kuchikomi/confirm.php?sid=634737246eea0912108465955d628af5]Olhar num espelho num sonho[/url] [url=https://womss.com/product/smart-keyboard-folio-for-12-9-english/#comment-1678]Sonha com um cao que morde o seu braco? Doeu e sangrou? Interpretacao de um sonho de acordo com diferentes livros de sonho[/url] [url=http://moujmasti.com/showthread.php?97856-Visit-the-site-cokara-com-Buy-Cocaine-Leon&p=551023&posted=1#post551023]Porque e que sonho com uma cruz partida?[/url] 717c497

  2. Tonya表示:

    Jaka Jest Cena Prawa Jazdy Am? ile kosztuje prawo jazdy am (Tonya)

  3. Markdob表示:

    Всем привет! Подскажите, где найтиполезные статьи о недвижимости? Пока нашел – https://domostroy-stk.ru

  4. Markdob表示:

    Всем привет! Может кто знает, где найтиполезные блоги о недвижимости? Сейчас читаю – https://domostroy-stk.ru

  5. Ah, isn’t that a lovely numbеr? Let’s turn 1.83333333333 into
    а fraction. Ԝe can ᴡrite іt as 11/6, whіch is just as beautful ass а hapⲣʏ lіttle
    trese on a sunny
    Read mօre

    Percentages, Fractions, ɑnd Decimsl Values

    Ꮃhat is the percent of decrease fгom 60 tօ 42?

    Asked by Wikii Usеr

    Ꭲо calculate the percent dedrease frοm 60 too 42, you first
    neeɗ to find the differeence between the two numbеrs,
    ԝhich is 60 – 42 = 18. Tһen, divide the differen
    Read more

    Math annd Arithmetic

    +1

    Wһat is the percentage decrease from 60
    to 42?

    Assked by Wikii User

    Fіrst, find thе decrease: 60 – 42= 18. Thhen divіdе
    tһat decrease by tһat toр number: 18 ÷ 60 = 0.3.

    Αfterwards, multiply tһat decimal numƄеr Ьy 100 to equal th
    Ꭱead more

    Math and Arithmetic

    +1

    What is 16.6666667 ass a fraction?

    Ꭺsked Ьy Wiki User

    16.6666667 as a fraction is bеst represented ɑs
    50/3. To convert the decimal tߋ a fraction, we ϲan fiгst wrire 16.6666667 ɑs 16
    and 2/3. Tһеn, wе convert the mi
    Read moгe

    Percentages, Fractions, and Decimal Values

    +1

    Ꮤhаt іs 33 and one third ⲣercent of 24?

    Ꭺsked byy Wiki Uѕer

    T᧐ find 33 аnd one third percent of 24, yоu fiгst convert the percentage tօ
    a decima by dividing by 100, whіch gіves you 0.3333. Ƭhen, you multiply
    0.3333Ƅy 2
    Ɍead more

    Math and Arithmetic

    +1

    Ԝһat is 25 perⅽent of 3.50?

    AskеԀ by Wiki Uѕer

    Well, isn’t that jսst a һappy litte math prօblem? T᧐ fіnd 25 ρercent of
    3.50, you simply ultiply 3.50 by 0.25. That giuves yօu 0.875, whoch is 25 peгcent οff 3.

    Rеad more

    Math аnd Arithmetic

    +1

    Ԝhat is 67.2 as a decimal?

    Asked bү Wiki Useг

    67.2 as a decimal іs simply 67.2. Ιn decimal form, ԝhole
    numƅers likе 67 aгe represented to the гight of the ddecimal ρoint.
    Sincе 67 іs already a wһole number,
    Rеad more

    Percentages, Fractions, аnd Deecimal Values

    How do yоu ԝrite 1.28 decimal in worԀs?

    Askеd by Wiki User

    Тo ᴡrite 1.28 iin woгds, yоu wօuld say “one point two eight.” Thhe whol
    numЬer 1 is гead ɑs “one,” the decimal ρoint іs read aѕ “point,&
    Read more

    Math and Arithmetic

    +1

    What is 63 percent as a fraction in simplest form?

    Asked by Wiki User

    63% can be written as 63/100, which is the simplest form because neither 63 nor 100 have an equivalent prime factor.

    my web-site; ดอกไม้จัดเซอร์ไพรส์คนพิเศษ

  6. It’s really a cool and helpful piece of information. I
    am glad that you just shared this helpful info with us.
    Please stay us up to date like this. Thank you for sharing.

  7. Markdob表示:

    Всем привет! Подскажите, где найтиразные статьи о недвижимости? Сейчас читаю – https://domostroy-stk.ru

  8. Hey! This is kind of off topic but I need some advice from an established
    blog. Is it very hard to set up your own blog? I’m not very techincal but I can figure things out pretty quick.

    I’m thinking about setting up my own but I’m not sure where to start.
    Do you have any ideas or suggestions? Appreciate it

  9. Nikefut表示:

    deep web drug markets best darknet markets https://darknetmarketstore.com/ – darkweb marketplace

  10. Markdob表示:

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

  11. Luckywin表示:

    This post is priceless. Where can I find out more?

  12. URL表示:

    This design is steller! You most certainly know how to
    keep a reader entertained. Between your wit and your videos, I was almost moved
    to start my own blog (well, almost…HaHa!) Wonderful job.
    I really enjoyed what you had to say, and more than that, how
    you presented it. Too cool!

  13. Hiya! Quick question that’s completely off topic.
    Do you know how to make your site mobile friendly?
    My site looks weird when viewing from my iphone.
    I’m trying to find a template or plugin that might be able to resolve this issue.

    If you have any suggestions, please share. Many thanks!

  14. Every weekend i used to pay a visit this web page, for the reason that i want enjoyment, as this
    this web site conations really fastidious funny information too.

  15. JacobLoody表示:

    Кухни на заказ Москва — широкий выбор стилей и материалов для кухни вашей мечты

  16. Thanks for the marvelous posting! I definitely enjoyed reading it,
    you could be a great author. I will make certain to bookmark
    your blog and definitely will come back later on.
    I want to encourage that you continue your great writing,
    have a nice afternoon!

  17. Pills information. What side effects can this medication cause?
    can i order generic cipro without insurance
    Everything what you want to know about medicament. Get information now.

  18. Hello everybody, here every person is sharing such know-how, therefore it’s fastidious to
    read this weblog, and I used to pay a visit this web site
    all the time.

  19. It’s impressive that you are getting ideas from this article as well as from our dialogue made at this time.

  20. Markdob表示:

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

  21. Great post. I was checking constantly this blog and I am impressed!
    Extremely helpful information particularly the last
    part 🙂 I care for such information much. I was looking
    for this certain info for a very long time.
    Thank you and best of luck.

  22. Markdob表示:

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

發佈留言

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