将对象数组按照某个键值排序

  arr=[{key:3,name:'name3'}, {key:2,name:'name2'}, {key:1,name:'name1'}, ]
  function compare(property: any) {
      return (a: any, b: any) => {
        const value1 = a[property];
        const value2 = b[property];
        return value1 - value2;
      };
  }

arr.sort(compare('key'));
// 输出  arr=[{key:1,name:'name1'}, {key:2,name:'name2'}, {key:3,name:'name3'},]

你可能感兴趣的:(将对象数组按照某个键值排序)