从简单排序到复杂场景,Array.sort()API全搞定

Array.sort () 是 JavaScript 中用于数组排序的核心 API,看似简单却能处理从基础到复杂的各种排序场景。它的核心在于通过自定义比较函数,灵活应对不同数据类型和业务需求。

一、基础用法与默认行为

Array.sort() 会直接修改原数组,并返回排序后的数组。默认排序规则是将元素转换为字符串,按 Unicode 码点顺序排序。

const arr = [10, 2, 21, 3];
arr.sort(); 
console.log(arr); // [10, 2, 21, 3] —— 按字符串"10""2""21""3"的码点排序

注意:默认排序对数字不友善,需通过比较函数自定义排序逻辑。

从简单排序到复杂场景,Array.sort()API全搞定

二、简单排序场景

1. 数字排序(升序 / 降序)

比较函数接收两个参数 a 和 b,返回值决定排序方向:

  • 返回 负数:a 排在 b 前面(升序)
  • 返回 正数:b 排在 a 前面(降序)
  • 返回 0:位置不变
const numbers = [3, 1, 4, 1, 5, 9];

// 升序(从小到大)
numbers.sort((a, b) => a - b); 
console.log(numbers); // [1, 1, 3, 4, 5, 9]

// 降序(从大到小)
numbers.sort((a, b) => b - a); 
console.log(numbers); // [9, 5, 4, 3, 1, 1]

2. 字符串排序(含大小写处理)

字符串排序可直接使用 localeCompare 方法,支持多语言排序规则,还能忽略大小写:

const words = ["Banana", "apple", "Cherry"];

// 按 Unicode 码点排序(默认,大写字母在小写前)
words.sort(); 
console.log(words); // ["Banana", "Cherry", "apple"]

// 按自然语言规则排序(忽略大小写)
words.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' })); 
console.log(words); // ["apple", "Banana", "Cherry"]

{ sensitivity: 'base' } 表明:仅区分不同的字符,忽略大小写和重音(如 a 与 A 视为相等)。

从简单排序到复杂场景,Array.sort()API全搞定

三、复杂场景:对象数组排序

实际开发中,我们常需要对对象数组按某个属性排序,例如按年龄、分数、日期等。

1. 单属性排序

假设有一个用户数组,需按 age 升序排列:

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

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

如果属性是字符串(如 name),则用 localeCompare:

// 按 name 字母序排序
users.sort((a, b) => a.name.localeCompare(b.name));

2. 多条件排序

当主条件相等时,按次要条件排序。例如:先按 score 降序,若分数一样则按 name 升序。

const students = [
  { name: "Bob", score: 85 },
  { name: "Alice", score: 90 },
  { name: "David", score: 85 },
  { name: "Charlie", score: 90 }
];

students.sort((a, b) => {
  // 主条件:按 score 降序
  if (b.score !== a.score) {
    return b.score - a.score;
  }
  // 次要条件:分数一样时,按 name 升序
  return a.name.localeCompare(b.name);
});

console.log(students);
// 输出顺序:Alice(90) → Charlie(90) → Bob(85) → David(85)

3. 嵌套对象属性排序

若对象属性是嵌套结构(如 address.city),直接访问嵌套属性即可:

const people = [
  { name: "Alice", address: { city: "Beijing" } },
  { name: "Bob", address: { city: "Shanghai" } },
  { name: "Charlie", address: { city: "Guangzhou" } }
];

// 按城市名称排序
people.sort((a, b) => a.address.city.localeCompare(b.address.city));

4. 自定义业务逻辑排序

针对特殊业务场景(如按状态优先级排序),可在比较函数中编写自定义规则。例如:按任务状态排序,优先级为 'done' > 'processing' > 'todo'。

const tasks = [
  { title: "Task 1", status: "todo" },
  { title: "Task 2", status: "done" },
  { title: "Task 3", status: "processing" },
  { title: "Task 4", status: "done" }
];

// 定义状态优先级映射
const statusPriority = { done: 2, processing: 1, todo: 0 };

tasks.sort((a, b) => {
  // 优先级高的排在前面(数值大的在前)
  return statusPriority[b.status] - statusPriority[a.status];
});

console.log(tasks);
// 输出顺序:done → done → processing → todo

从简单排序到复杂场景,Array.sort()API全搞定

四、注意事项

  1. 原数组修改:sort() 会直接修改原数组,若需保留原数组,可先复制:
  2. javascript
  3. 运行
  4. const sorted = […originalArray].sort(comparator); // 用扩展运算符复制
  5. 稳定性:ES2019 后,sort() 是稳定排序(相等元素的相对顺序不变),适合多轮排序。
  6. 特殊值处理:排序包含 null、undefined 或 NaN 的数组时,这些值会被排在末尾(null 和 undefined 视为相等,NaN 排在最后)。

总结

Array.sort() 的核心是比较函数,通过灵活设计比较逻辑,可处理从基础数字 / 字符串排序到复杂对象、多条件、自定义业务规则的排序场景。掌握它能极大提升数组处理效率。

从简单排序到复杂场景,Array.sort()API全搞定

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
none
暂无评论...