一、数组排序
const arr = [1, 11,22,2,3,33]
// 升序
arr.sort(function(a, b) {
return a - b
})
// 降序
arr.sort(function(a, b) {
return b - a
})
二、数组对象排序
const arrObj = [
{
name: '张三',
age: 25
},
{
name: '李四',
age: 30
},
{
name: '王五',
age: 28
}
]
// 升序
function ascending(age) {
return function(a, b) {
let val1 = a[age]
let val2 = b[age]
return val1 - val2
}
}
console.log(arrObj.sort(ascending('age')))
// 降序
function descending(age) {
return function(a, b ) {
let val1 = a[age]
let val2 = b[age]
return val2 - val1
}
}
console.log(arrObj.sort(descending('age')))