Home > Web Front-end > JS Tutorial > body text

js code to sort according to a certain attribute of the object (such as: name, age)_javascript skills

WBOY
Release: 2016-05-16 18:21:45
Original
1002 people have browsed it
Copy code The code is as follows:

//Define an object array
 var data = [{ name : "jiang", age: 22 }, { name: "AAAAAAAAAAAAAAA", age: 21 }, { name: "CCCCCCCCCc", age: 25}];
  //Define a comparator
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
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template