A JS code that sorts according to an attribute of an object (e.g. Name,age) _javascript tips

Source: Internet
Author: User
Copy Code code as follows:

Define an array of objects
var data = [{name: ' Jiang ', age:22}, {name: ' Aaaaaaaaaaaaaa ', age:21}, {name: ' CCCCCCCCC ', age:25}];
Define a comparer
function Compare (PropertyName) {
return function (Object1, object2) {
var value1 = Object1[propertyname];
var value2 = Object2[propertyname];
if (value2 < value1) {
return-1;
}
else if (value2 > value1) {
return 1;
}
else {
return 0;
}
}
}
How to use
Data.sort (Compare ("name"));
alert (data[0].name);//jiang
How to use
Data.sort (Compare ("age"));
alert (data[0].age);//25s

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.