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,372,430 Responses

  1. The Reason Why Erbs Palsy Attorney Is Everyone’s Obsession In 2024 Attorney injury lawyer

  2. kong88bet表示:

    This is really fascinating, You’re an excessively skilled blogger.

    I have joined your rss feed and stay up for in the hunt for more of your
    fantastic post. Additionally, I have shared your
    site in my social networks

  3. Jesse Hale表示:

    Grooming my pet dog used to be a chore mobile dog grooming prices

  4. How To Outsmart Your Boss On Key Reprogramming
    key reprogramming near me

  5. 10 Wrong Answers For Common Folding Mobility Scooters Uk Questions: Do You Know The Right Answers?
    Lightweight Foldable Mobility Scooter Uk

  6. Hi, Neat post. There is a problem with your web site in internet explorer, would check this? IE still is the market leader and a good portion of people will miss your wonderful writing due to this problem.

  7. telegra.ph表示:

    See What Treadmills Best Tricks The Celebs Are Utilizing Treadmills best
    (telegra.ph)

  8. homepage表示:

    Получайте кэшбэк до 5% на каждый покупку
    с картой Сбербанка! Экономьте на покупках в магазинах,
    кафе и онлайн. Простое оформление и удобное
    управление через мобильное приложение.

    Начните экономить уже сегодня!======>

    Совкомбанк – Дебетовая карта с кешбэком в Арзамасе

  9. sex hentai表示:

    Thanks very nice blog!

  10. Mabelle Owens表示:

    This article really opened my eyes about what to look for in an auto body shop—###ANYKEYWORD### seems towing

  11. Ollie Holmes表示:

    Limos aren’t simply for celebrities anymore! They make every celebration really feel unique. Have you tried renting one for a birthday or wedding anniversary? Take a look at even more regarding it at best Austin limo service

  12. Max Cortez表示:

    I was pleasantly surprised by how quickly ### anyKeyWord### responded and assisted us with our urgent needs concerning bail Bail bonds

  13. E2Bet PKR表示:

    I’ve been using E2Bet for a while now, and it’s the best platform for cricket exchange in Pakistan! The live odds are accurate, and
    the user interface is seamless. Highly recommend it to
    everyone!

  14. I used to be recommended this website through my cousin.
    I’m now not sure whether this submit is written via him as nobody else realize such specific approximately my trouble.
    You are incredible! Thank you!

  15. Hello there! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good success.

    If you know of any please share. Appreciate it!

  16. OP表示:

    Karaoke Bar OP

  17. Wonderful website you have here but I was curious about if
    you knew of any message boards that cover the same topics discussed
    here? I’d really love to be a part of group where I can get comments from other experienced
    individuals that share the same interest. If you have any recommendations, please let
    me know. Kudos!

發佈留言

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