sort对象数组排序

时间:2023-03-09 01:45:26
sort对象数组排序
function objectSort(property, desc) {
//降序排列
if (desc) {
return function (a, b) {
return (a[property] > b[property]) ? -1 : (a[property] < b[property]) ? 1 : 0;
}
}
return function (a, b) {
return (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
}
}

  eg:var myArray = [ { "name": "John Doe", "age": 29 }, { "name": "Anna Smith", "age": 24 }, { "name": "Peter Jones", "age": 39 } ]

execute:myArray.sort(objectSort('name',true));

result:

sort对象数组排序