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,375,602 Responses

  1. How To Market On The Online World 에볼루션 롤링;
    humanlove.stream,

  2. Very energetic article, I loved that bit.
    Will there be a part 2?

  3. a22表示:

    It’s really a nice and helpful piece of info.
    I’m happy that you simply shared this useful info with us.
    Please stay us up to date like this. Thanks for
    sharing.

  4. план перепланировки квартиры для согласования https://zakazat-proekt-pereplanirovki-kvartiry11.ru/ .

  5. Just completed my fencing project with an amazing team from Melbourne recommended by Chain link fencing contractors #—so

  6. MiguelUnind表示:

    https://prednibest.com/# cost of prednisone in canada

  7. DanielAbice表示:

    https://amoxstar.com/# buy amoxicillin without prescription

  8. Ross表示:

    Here is my website dating app with most marriages (Ross)

  9. Isaiah Neal表示:

    Your mention of market research as a foundational step in growth is so true! Explore further insights at local seo

  10. Grace Gilbert表示:

    Pressure cleaning is the very best method to restore your home’s outside! I recommend attempting it out. For excellent services, check out expert pressure washing service

  11. Lucile Hayes表示:

    Eco-friendly dumpster rentals are the future! Got mine from dumpster rental orlando

  12. DanielAbice表示:

    http://amoxstar.com/# amoxicillin 500mg price in canada

  13. Nikefut表示:

    dark web market list tor darknet dark market onion

  14. Pills prescribing information. What side effects?
    how to get generic ipratropium without dr prescription
    Everything about drug. Read information here.

  15. RobertJar表示:

    ciprofloxacin 500 mg tablet price: CiPharmDelivery – buy cipro online

  16. Eunice Foster表示:

    En god samtale med ens frisør kan gøre hele oplevelsen bedre! Frisør Valby – Joanna Zabell

  17. KennethPah表示:

    prednisone 250 mg prednisone price where can you buy prednisone

  18. arabian news表示:

    Thanks for one’s marvelous posting! I really enjoyed reading it,
    you could be a great author.I will be sure to bookmark your blog and will
    eventually come back in the future. I want to encourage continue your great posts, have a nice day!

  19. Your way of explaining all in this post is really pleasant, all be able to without difficulty
    understand it, Thanks a lot.

  20. RobertJar表示:

    cipro for sale: ci pharm delivery – buy cipro

  21. сколько стоит проект перепланировки квартиры в москве сколько стоит проект перепланировки квартиры в москве .

  22. It may likewise be an excellent idea to hire a land surveyor prior to developing any type of land, prior to purchasing land or residential property, and prior to including a fence or roadway to your property. At times, a survey of the residential property can be found by doing a title search or by looking regional records, but often these studies might be old. If you are dealing with a boundary dispute, among the steps you might require to take is to employ a property surveyor to execute a brand-new survey.
    Failing to resolve such disputes might discourage several potential customers and home loan lenders from considering your residential or commercial property, as they might view it as a prospective responsibility. Offering a building with an unresolved limit conflict is lawfully acceptable, however it’s important to divulge this details to possible buyers as mandated by law. For instance, an utility easement gives energy business accessibility to mount and keep utility lines on personal property. Nevertheless, it’s far better to disclose than keep info from prospective customers to stop claims in the future. In this case, the vendor fell short to divulge a next-door neighbor dispute when marketing the building. The concerns with the neighbor were ongoing and had actually also led to the house owner calling the authorities on occasion.
    The Line of Actual Control does not represent what each government cases, yet what they in fact regulate. The contemporary federal governments of the Republic of India and individuals’s Republic of China have used up the disagreement, and the problem appears primarily to entail the principle of the important things. While both areas do bring something to the table in terms of armed forces method, agriculture, and mining, neither really add that much to the economic climate or conventional society of either India or China. Actually, the border regions are home to numerous ethnic teams that have little link to the Hindu-oriented society of India or the Han-oriented society of China, consisting of the Nyishi, Uyghur, and Tibetans. The Actual Irish Republican Army and other terrorist companies dedicated acts of fear throughout the UK in objection of the political limit dividing UK-controlled Northern Ireland from the remainder of Ireland.
    This disagreement may happen when multiple treaties (or other lawful documents) specifying where borders ought to be attracted are active all at once, but negate each other. This may be the result of a negative land study and even a misunderstanding of the border being asserted by the other party. A boundary disagreement is a dispute concerning the specific area of a building’s border. In some cases individuals develop boundaries with verbal contracts or based upon incorrect dimensions. These issues can intensify in time and cause a limit conflict in the future. Numerous concerns can cause border disagreements, and the law has certain ways to take care of each kind.

    Due to the fact that easements “run with the land,” it suggests they automatically transfer to you as the homeowner when you buy the land. Easements can be ended in a range of methods, but there are comprehensive legitimacies to doing it properly. Sometimes it’s as straightforward as dissolving an easement where the land concerned has actually been deserted.
    Sorts Of Easements

    Common instances of easements include civil liberties of means, rights to light, and civil liberties to access utilities. So while the 2003 Act has gone a significant means to clearing up the general public’s right to be ashore coming from others, there are still aspects of basic rights of access taking that would certainly benefit from more statutory explanation. The court can additionally identify if public gain access to civil liberties have been used properly, or irresponsibly. This can be a helpful device for landowners and land users alike in settling disagreements about accountable use of land. As an example, you might legitimately approve next-door neighbors access to cross your property to reach the public park behind your home. In this instance, the easement becomes part of the public record of your property and reaches all future owners of your residential or commercial property unless legitimately transformed by them.
    What Happens If I Build On An Easement?
    They must make use of and handle their land in an accountable means, having regard to the legal rights of the public. It is very important to keep in mind that public gain access to rights apply in metropolitan and sub-urban areas as well. As their names recommend, affirmative easements permit the easement owner to make use of the land in a certain method, while unfavorable easements protect against the easement holder from making use of the land in a specific method. The instance of permitting residents of a landlocked property to go across one more property to access an exclusive road would be an affirmative easement, due to the fact that it allows its owner to do something. An example of an unfavorable easement can be concurring not to block a sight by developing a fencing or constructing a tall building– in this situation, the easement avoids a specific usage. Preserving a right of way for public access or utility firms is the duty of the land proprietor.

發佈留言

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