js实现链式排序
链式排序的实现方法
链式排序(Chained Sorting)允许通过多个条件对数组进行连续排序。JavaScript 的 Array.prototype.sort() 方法可以结合自定义比较函数实现链式排序逻辑。
基础链式排序实现
定义一个通用的链式排序函数,支持多个排序条件的组合:
function chainSort(array, ...comparators) {
return array.slice().sort((a, b) => {
for (const compare of comparators) {
const result = compare(a, b);
if (result !== 0) return result;
}
return 0;
});
}
使用示例:
const users = [
{ name: "Alice", age: 25, score: 85 },
{ name: "Bob", age: 25, score: 90 },
{ name: "Charlie", age: 30, score: 80 }
];
// 先按年龄升序,再按分数降序
const sorted = chainSort(
users,
(a, b) => a.age - b.age,
(a, b) => b.score - a.score
);
动态条件链式排序
创建更灵活的链式排序方法,支持动态指定排序字段和方向:
function dynamicChainSort(array, ...conditions) {
return array.slice().sort((a, b) => {
for (const { key, desc = false } of conditions) {
if (a[key] < b[key]) return desc ? 1 : -1;
if (a[key] > b[key]) return desc ? -1 : 1;
}
return 0;
});
}
使用示例:
const sortedUsers = dynamicChainSort(
users,
{ key: 'age' },
{ key: 'score', desc: true }
);
链式方法实现
通过扩展 Array 原型实现链式调用风格:
Array.prototype.chainSort = function(...comparators) {
return this.slice().sort((a, b) => {
for (const compare of comparators) {
const result = compare(a, b);
if (result !== 0) return result;
}
return 0;
});
};
// 使用方式
const result = users
.chainSort(
(a, b) => a.age - b.age,
(a, b) => b.score - a.score
);
性能优化建议
对于大型数据集,考虑以下优化措施:
- 预先计算比较用的关键值
- 避免在比较函数中创建新对象
- 对稳定排序有要求时使用特殊算法
链式排序的核心思想是通过多个比较函数的串联实现多条件排序,每个比较函数只在上一级比较相等时才发挥作用。







