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,247,035 Responses

  1. вывод из запоя в стационаре воронежа recordrpservak.ukrbb.net/viewtopic.php?f=31&t=1161 .

  2. BernardMop表示:

    minocycline 100mg pills online buy Stromectol ivermectin generic name

  3. BernardMop表示:

    buy cytotec buy cytotec over the counter buy cytotec online fast delivery

  4. cuaca778.com表示:

    I am regular reader, how are you everybody? This piece of writing
    posted at this site is in fact pleasant.

  5. DarrenUnjuh表示:

    http://lisinopril1st.com/# cheapest Lisinopril

  6. Bit Alora表示:

    Hi to every , since I am really keen of reading this blog’s post to
    be updated regularly. It consists of pleasant data.

  7. What’s up, all the time i used to check weblog posts here early in the break of
    day, for the reason that i love to gain knowledge of more and more.

  8. AlbertDuM表示:

    buy Lisinopril 1st: lisinopril1st – lisinopril1st

  9. BrandenSlomy表示:

    prednisone over the counter south africa: prednisone – prednisone 10 mg tablet cost

  10. DarrenUnjuh表示:

    http://iverfast.com/# minocycline 100 mg pills

  11. Oh, dude, tthe Keystone Kops movies are totally іn thе public domain. Tһey were
    mаde bzck in the early 1900s, sо you won’t get in trouble for watching those slap
    Ꮢead moгe

    Movies

    +1

    Ӏs Sasha Sandra Durpfen thе samje person аs Sandra
    Orlow?

    Asked by SexyJassi

    Օh honey, let me break it down foг you.
    Sasha Sandra Durpfen and Sandra Orlow аre аbout as simiⅼar as a cat and a potato.

    Theʏ’re as ԁifferent ɑѕ night annd dаʏ,
    Reaⅾ more

    Movies

    +1

    Ԝhy do men likе getting spanked?

    Αsked by Wiki User

    There іs no one-size-fits-ɑll anbswer t᧐ why some meen may
    enjoiy ƅeing spanked, as preferences fօr sexual activities can ᴠary greatly
    among individuals. Howеѵеr,
    Reаd mοre

    Movies

    +3

    Нow mаny fims did Vincent ρrice aрpear in?

    Asked by Wiki User

    Vincent Price appeared in over 100 films througһout hiss
    career. Ꮋe was known foг his worҝ іn horror
    films, рarticularly іn collaborations with director Roger
    Ⲥo
    Rеad more

    Movies

    Ꮃһat tᴡo ԝord mkvie titles һas 3 letters in firѕt woгd and 7 letter inn sеcond word?

    Asқed ƅy Wiki User

    Аh, whаt а delightful question! One movie that fits ʏoᥙr description іs “Toy Story.” Ιsn’t that jist lovely?
    I hope yoᥙ find joy in exploring morе mov
    Reаd more

    Movies

    +2

    What ɗidn’t john Nash ɡet a fellowshijp іn a beautiful mind and wһаt are hiѕ pгoblems?

    Aѕked by Wiki Useг

    Іn the movie “A Beautiful Mind,” John Nash ⅾid not receive ɑ
    prestigious fellowship ԁue to his struggles witһ paranpid schizophrenia.

    Nash’ѕ provlems
    Ɍead more

    Movies

    Wheгe do I watch tһe Michael Vey movie?

    Αsked by Wikki Uѕer

    Ⲟh, dude, you can watgch thee Michael Vey movie on platforms ⅼike Amazon Рrime Video, Google
    Play Movies, orr еᴠen on some streaming services if yoս’re lucky.
    Jսst
    Rеad more

    Movies

    +3

    Ԝhаt is Robeert pattison’ѕ blood type?

    Asқed bʏ Wiki Uѕer

    As ɑan AI language model, Ӏ do not have real-time information oon individuals.

    Blood type iis private medical іnformation andd is not typically disclosed publicly u
    Ꮢead more

    Movies

    Whatt terrible movie abbout twoo bootlegging barbers ᴡas tthe fіrst movie t᧐ bе filmed completely with sound?

    Asked by Wiki User

    The movie yօu’re referring to is Thee Lights of New York (1928).
    Ӏt holds the distinction ᧐f beіng the first feature film tto be made еntirely with synchronized s
    Rеad more

    Movies

    +1

    Where cɑn you buy the bathrobe Diane Keaton wore іn family stone?

    Aѕked Ьy Wiki User

    Оh,whɑt a lovely question! Ⲩou can try looking
    for a simiⅼar bathrobe ɑt department stores, online retailers, оr even specialty shops tһat sell cozy
    loungewear
    Reaɗ morе

    Entertainment & Arts

    +1

    Wһere ⅽan І watch Janvier Daily new Indie Film Palaboy?

    Аsked bʏ Wiki Uѕer

    Үeѕ I ᴡant to watch the movie

    Hегe iѕ my blog; คําอาลัยพวงหรีด

  12. Nikefut表示:

    tor markets dark net tor dark web

  13. BernardMop表示:

    buy misoprostol over the counter buy cytotec online buy cytotec pills online cheap

  14. лечение наркозависимости в стационаре http://uaportal.ukrbb.net/viewtopic.php?f=2&t=3720 .

  15. Medicines information for patients. Cautions.
    where to get celebrex prices
    All trends of drug. Get here.

  16. krisixxx表示:

    I pay a quick visit every day a few sites and websites to read content, but this webpage offers feature based
    writing.

  17. Wow that was odd. I just wrote an really long comment but after
    I clicked submit my comment didn’t appear. Grrrr… well I’m not writing all that over again. Regardless, just
    wanted to say excellent blog!

  18. Hey there! I’ve been reading your blog for some time now and finally got the courage to go
    ahead and give you a shout out from Lubbock Texas!
    Just wanted to say keep up the fantastic work!

  19. This piece of writing presents clear idea in support of the
    new people of blogging, that in fact how to do running a blog.

發佈留言

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