js实现链式排序
链式排序的实现方法
链式排序允许通过连续调用多个排序条件对数组进行多级排序。以下是几种实现方式:

使用 Array.prototype.sort 和链式调用
const data = [
{ name: 'Alice', age: 25, score: 90 },
{ name: 'Bob', age: 30, score: 85 },
{ name: 'Alice', age: 20, score: 95 }
];
function chainSort(arr) {
let sortFunctions = [];
const sorter = {
by: function(prop, direction = 'asc') {
sortFunctions.push((a, b) => {
if (a[prop] < b[prop]) return direction === 'asc' ? -1 : 1;
if (a[prop] > b[prop]) return direction === 'asc' ? 1 : -1;
return 0;
});
return this;
},
execute: function() {
return arr.slice().sort((a, b) => {
for (const fn of sortFunctions) {
const result = fn(a, b);
if (result !== 0) return result;
}
return 0;
});
}
};
return sorter;
}
// 使用示例
const sorted = chainSort(data)
.by('name')
.by('age', 'desc')
.by('score', 'asc')
.execute();
使用函数式编程风格
function createSorter(...sorters) {
return (a, b) => {
for (const sorter of sorters) {
const result = sorter(a, b);
if (result !== 0) return result;
}
return 0;
};
}
const byName = (a, b) => a.name.localeCompare(b.name);
const byAgeDesc = (a, b) => b.age - a.age;
const byScore = (a, b) => a.score - b.score;
const sorter = createSorter(byName, byAgeDesc, byScore);
const sorted = [...data].sort(sorter);
使用 ES6 类实现
class ChainSorter {
constructor(arr) {
this.arr = arr;
this.sorters = [];
}
by(prop, direction = 'asc') {
this.sorters.push((a, b) => {
if (a[prop] < b[prop]) return direction === 'asc' ? -1 : 1;
if (a[prop] > b[prop]) return direction === 'asc' ? 1 : -1;
return 0;
});
return this;
}
execute() {
return [...this.arr].sort((a, b) => {
for (const sorter of this.sorters) {
const result = sorter(a, b);
if (result !== 0) return result;
}
return 0;
});
}
}
// 使用示例
const sorter = new ChainSorter(data);
const result = sorter
.by('name')
.by('age', 'desc')
.execute();
实现要点
- 链式调用通过在每个方法中返回
this实现 - 多级排序通过维护排序函数数组实现
- 每次排序比较时按顺序应用所有排序条件
- 原始数组不会被修改,执行时创建副本
- 支持升序和降序两种排序方向
这些方法都可以根据实际需求进行扩展,比如添加自定义比较函数、支持更复杂的排序逻辑等。






