How to extend the OrderByAsc and OrderByDesc methods of js object arrays _ javascript skills

Source: Internet
Author: User
Js extension methods are prototype-based, such as Array. prototype. XXXX is to extend the XXX Method to the Array, and then the Array can use this method. In the object Array, there are often sorting, ascending, and descending by attribute, next I will share with you a piece of knowledge I have written about the js prototype for a while. The js extension method is based on the prototype, such as Array. prototype. XXXX is to extend the XXX Method to the Array, and then the Array can use this method.

In the object array, attributes are often sorted in ascending or descending order, so I want to write a method similar to orderBy in C #. The Code is as follows:

The Code is as follows:


Array. prototype. OrderByAsc = function (func ){
Var m = {};
For (var I = 0; I <this. length; I ++ ){
For (var k = 0; k <this. length; k ++ ){
If (func (this [I]) <func (this [k]) {
M = this [k];
This [k] = this [I];
This [I] = m;
}
}
}
Return this;
}
Array. prototype. OrderByDesc = function (func ){
Var m = {};
For (var I = 0; I <this. length; I ++ ){
For (var k = 0; k <this. length; k ++ ){
If (func (this [I])> func (this [k]) {
M = this [k];
This [k] = this [I];
This [I] = m;
}
}
}
Return this;
}


The call method is as follows:

The Code is as follows:


Var arr = [{name: 'aaa', grade: 20}, {name: 'ccc ', grade: 30}, {name: 'bbb', grade: 40}];
Var orderArr = arr. OrderByDesc (function (){
Return a. grade;
});


Then, let's output the result:

The Code is as follows:


For (var I = 0; I <orderArr. length; I ++ ){
Document. write (orderArr [I]. name );
}


I am a js newbie. If you have any ideas, leave a message and exchange ideas with each other.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.