// 编写函数使得familys对象数组可根据age、commentnum来进行降序排序并返回新的数组(排序字段优先级age、commentnum)。
let familys = [{
name: 'JavaScript',
age: 26,
commentnum: 699
}, {
name: 'HTML',
age: 26,
commentnum: 996
}, {
name: 'CSS',
age: 25,
commentnum: 700
}, {
name: 'Vue',
age: 7,
commentnum: 1024
}, {
name: 'React',
age: 8,
commentnum: 1618
}];
1. 方法一:使用for冒泡排序
function compare(p1, p2) {
//待补充
let a = familys
for (let i = a.length - 1; i >= 0; i--) {
for (let j = 0; j < i; j++) {
if (a[j][p1] <= a[j + 1][p1] && a[j][p2] < a[j + 1][p2]) {
[a[j], a[j + 1]] = [a[j + 1], a[j]]
}
}
}
return (a, b) => {
return b - a
}
}
// console.log(compare("age", "commentnum"));
console.log(familys.sort(compare("age", "commentnum")));;
2. 方法二:使用sort方法进行排序
function compare(p1, p2) {
return (a, b) => {
if (a[p1] == b[p1]) {
return b[p2] - a[p2]
} else {
return b[p1] - a[p1]
}
}
}
console.log(familys.sort(compare("age", "commentnum")));;