当前位置:首页 > JavaScript

js实现链式排序

2026-04-04 14:38:26JavaScript

链式排序的实现方法

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

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();

实现要点

  1. 链式调用通过在每个方法中返回this实现
  2. 多级排序通过维护排序函数数组实现
  3. 每次排序比较时按顺序应用所有排序条件
  4. 原始数组不会被修改,执行时创建副本
  5. 支持升序和降序两种排序方向

这些方法都可以根据实际需求进行扩展,比如添加自定义比较函数、支持更复杂的排序逻辑等。

标签: 链式js
分享给朋友:

相关文章

js实现打印

js实现打印

使用window.print()方法实现打印 在JavaScript中,可以通过调用window.print()方法直接触发浏览器的打印功能。这会打开系统的打印对话框,用户可以选择打印机和设置打印选项…

js 实现vue

js 实现vue

Vue.js 的基本实现 在 JavaScript 中实现 Vue.js 的核心功能,可以通过数据绑定、响应式系统和虚拟 DOM 来实现。以下是实现 Vue.js 核心功能的简化版本。 数据响应式系…

js实现二叉树

js实现二叉树

二叉树的基本概念 二叉树是一种树形数据结构,每个节点最多有两个子节点,分别称为左子节点和右子节点。二叉树的常见操作包括插入、删除、遍历等。 二叉树的节点定义 在JavaScript中,二叉树的节点可…

js实现驼峰

js实现驼峰

实现驼峰命名的几种方法 使用正则表达式和字符串替换 通过正则表达式匹配字符串中的特定模式(如下划线或短横线),并将其后的字母转换为大写,同时移除分隔符。 function toCamelCase(s…

js实现防洪

js实现防洪

防抖(Debounce)实现 防抖的核心思想是在事件触发后延迟执行回调函数,若在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口调整等场景。 function debounce(func,…

js手势实现

js手势实现

手势识别实现方法 在JavaScript中实现手势识别通常涉及监听触摸事件(touchstart、touchmove、touchend)或鼠标事件(mousedown、mousemove、mouseu…