1. // 编写函数使得familys对象数组可根据age、commentnum来进行降序排序并返回新的数组(排序字段优先级age、commentnum)。
  2. let familys = [{
  3. name: 'JavaScript',
  4. age: 26,
  5. commentnum: 699
  6. }, {
  7. name: 'HTML',
  8. age: 26,
  9. commentnum: 996
  10. }, {
  11. name: 'CSS',
  12. age: 25,
  13. commentnum: 700
  14. }, {
  15. name: 'Vue',
  16. age: 7,
  17. commentnum: 1024
  18. }, {
  19. name: 'React',
  20. age: 8,
  21. commentnum: 1618
  22. }];

1. 方法一:使用for冒泡排序

  1. function compare(p1, p2) {
  2. //待补充
  3. let a = familys
  4. for (let i = a.length - 1; i >= 0; i--) {
  5. for (let j = 0; j < i; j++) {
  6. if (a[j][p1] <= a[j + 1][p1] && a[j][p2] < a[j + 1][p2]) {
  7. [a[j], a[j + 1]] = [a[j + 1], a[j]]
  8. }
  9. }
  10. }
  11. return (a, b) => {
  12. return b - a
  13. }
  14. }
  15. // console.log(compare("age", "commentnum"));
  16. console.log(familys.sort(compare("age", "commentnum")));;

2. 方法二:使用sort方法进行排序

  1. function compare(p1, p2) {
  2. return (a, b) => {
  3. if (a[p1] == b[p1]) {
  4. return b[p2] - a[p2]
  5. } else {
  6. return b[p1] - a[p1]
  7. }
  8. }
  9. }
  10. console.log(familys.sort(compare("age", "commentnum")));;