var arr = [
{
id: 1,
name: "张三",
score: 100,
},
{
id: 1,
name: "李四",
score: 45,
},
{
id: 1,
name: "王金",
score: 23,
}
]
const compare = (property, desc = "asc") => {
return function (a, b) {
let value1 = a[property], value2 = b[property]
if (desc === "desc") { //降序
return value2 - value1
} else { //升序
return value1 - value2
}
}
}
console.log(arr.sort(compare("score")))
compare方法的第一个参数是待排序的字段名,第二个参数可选,默认是升序,若是降序,则需传入"desc"
单词:
ascending order :升序
descending order :降序