通过Array.prototype添加自定义方法来实现
下面是代码试例
1.sortBy方法,
根据指定的属性进行升序排序。
Array.prototype.sortBy = function (property) {
return this.sort((a, b) => a[property] - b[property]);
};
2.sortByDesc方法,根据指定的属性进行降序排序。
Array.prototype.sortByDesc = function (property) {
return this.sort((a, b) => b[property] - a[property]);
};
3.sortByFn方法,根据自定义比较函数进行排序。
Array.prototype.sortByFn = function (compareFn) {
return this.sort(compareFn);
};
下面是使用实例
const arr = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
{ name: 'Adam', age: 20 }
];
arr.sortBy('age');
console.log(arr); // [{ name: 'Adam', age: 20 }, { name: 'John', age: 25 }, { name: 'Jane', age: 30 }]
arr.sortByDesc('age');
console.log(arr); // [{ name: 'Jane', age: 30 }, { name: 'John', age: 25 }, { name: 'Adam', age: 20 }]
arr.sortByFn((a, b) => a.name.localeCompare(b.name));
console.log(arr); // [{ name: 'Adam', age: 20 }, { name: 'Jane', age: 30 }, { name: 'John', age: 25 }]