使用sort根据数组中对象的某个属性值进行排序
var array = [
{
id: 1,
name: 'zhangsan',
age: 21
},
{
id: 4,
name: 'liuliu',
age: 19
},
{
id: 3,
name: 'wangwu',
age:35
},
{
id: 2,
name: 'lisi',
age: 23
}
]
function setarray(array) {
array.sort(Compare('id'))
return array
}
function Compare(property) {
return function (a,b) {
return a[property] - b[property]
}
}
console.log(setarray(array));