本文实例讲述了JS实现json数组排序操作。分享给大家供大家参考,具体如下:
有时需要根据json对象的某个属性排序json数组,javascript端有sort这个函数,具体可以参考:http://www.w3school.com.cn/jsref/jsref_sort.asp
我们可以传入一个对比函数,我实现了两个:一个降序排列,一个升序排列
/**
* json对象数组按照某个属性排序:降序排列
* @param {Object} propertyName
*/
function compareDesc(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;
}
}
}
/**
* json对象数组按照某个属性排序:升序排列
* @param {Object} propertyName
*/
function compareAsc(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;
}
}
}
例子:
var students=[{name:"hhhh",age:16},{name:"ggggg",age:17},{name:"dsdsad",age:18}];
students.sort(compareDesc("age")); //按照年龄降序排列
console.log(students);
运行结果:
var students=[{name:"hhhh",age:16},{name:"ggggg",age:17},{name:"dsdsad",age:18}];
students.sort(compareAsc("age")); //按照年龄升序排列
console.log(students);