当前位置:首页 > JavaScript

js实现sort

2026-01-31 23:46:42JavaScript

实现 JavaScript 的排序功能

JavaScript 提供了 Array.prototype.sort() 方法来实现数组排序。该方法默认将元素转换为字符串后按 Unicode 码点排序,但可以通过自定义比较函数实现更复杂的排序逻辑。

基本用法(默认排序)

默认情况下,sort() 方法会将数组元素转换为字符串后排序:

const fruits = ['banana', 'apple', 'orange', 'grape'];
fruits.sort();
console.log(fruits); // ['apple', 'banana', 'grape', 'orange']

对于数字数组,默认排序可能不符合预期:

const numbers = [10, 2, 5, 1, 9];
numbers.sort();
console.log(numbers); // [1, 10, 2, 5, 9](按字符串比较)

自定义比较函数

要实现数字排序或其他自定义排序,需要提供比较函数:

const numbers = [10, 2, 5, 1, 9];
numbers.sort((a, b) => a - b); // 升序
console.log(numbers); // [1, 2, 5, 9, 10]

numbers.sort((a, b) => b - a); // 降序
console.log(numbers); // [10, 9, 5, 2, 1]

比较函数应返回:

js实现sort

  • 负数:a 应排在 b 前面
  • 正数:b 应排在 a 前面
  • 0:顺序不变

对象数组排序

对于对象数组,可以基于对象属性排序:

const users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 20 }
];

users.sort((a, b) => a.age - b.age); // 按年龄升序
console.log(users);
// [
//   { name: 'Charlie', age: 20 },
//   { name: 'Alice', age: 25 },
//   { name: 'Bob', age: 30 }
// ]

字符串排序(区分大小写)

默认的字符串排序区分大小写(大写字母排在小写字母前面):

const words = ['apple', 'Banana', 'cherry', 'Date'];
words.sort();
console.log(words); // ['Banana', 'Date', 'apple', 'cherry']

要实现不区分大小写的排序:

js实现sort

words.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' }));
console.log(words); // ['apple', 'Banana', 'cherry', 'Date']

稳定排序

从 ES2019 开始,sort() 被要求是稳定排序(相同值的元素保持原始相对顺序):

const data = [
  { value: 1, order: 1 },
  { value: 2, order: 2 },
  { value: 1, order: 3 }
];

data.sort((a, b) => a.value - b.value);
console.log(data);
// [
//   { value: 1, order: 1 },
//   { value: 1, order: 3 },
//   { value: 2, order: 2 }
// ]

性能注意事项

sort() 的时间复杂度取决于具体实现,现代浏览器通常使用 TimSort 或类似算法,平均时间复杂度为 O(n log n)。对于大型数组,可能需要考虑性能优化。

实现自定义排序算法

虽然通常建议使用内置的 sort() 方法,但了解排序算法实现也有价值。以下是快速排序的 JavaScript 实现:

function quickSort(arr) {
  if (arr.length <= 1) return arr;
  const pivot = arr[0];
  const left = [];
  const right = [];
  for (let i = 1; i < arr.length; i++) {
    arr[i] < pivot ? left.push(arr[i]) : right.push(arr[i]);
  }
  return [...quickSort(left), pivot, ...quickSort(right)];
}

const nums = [5, 3, 8, 4, 2];
console.log(quickSort(nums)); // [2, 3, 4, 5, 8]

标签: jssort
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。 // 方…

js实现倒计时

js实现倒计时

使用 setInterval 实现倒计时 通过 setInterval 定时器每秒更新剩余时间,适用于简单倒计时场景。 function countdown(seconds, callback) {…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

js节流实现

js节流实现

节流的概念 节流(Throttle)是一种限制函数执行频率的技术,确保函数在一定时间间隔内只执行一次。常用于滚动事件、窗口调整等高频触发的场景。 基础实现方法 使用时间戳判断是否执行函数: fun…

js实现吸色

js实现吸色

使用Canvas实现吸色功能 通过Canvas的getImageData方法获取像素颜色数据。创建一个Canvas元素,将目标图像绘制到Canvas上,通过鼠标事件获取坐标对应的颜色值。 c…

js分页实现

js分页实现

分页的基本原理 分页的核心是通过计算当前页码和数据偏移量,从服务器或本地数据中截取对应范围的数据进行展示。通常需要以下参数:当前页码(currentPage)、每页条数(pageSize)、总数据量(…