sort() = method used to sort element of an array in place
sorts elements as string in lexicographic order, not alphabetical exicographic = (alphabet + numbers + symbols) as strings
sort string
// ======================== 1️⃣ 字符串排序 ========================
// 定义一个字符串数组
let fruits = ["apple", "orange", "banana", "coconut", "pineapple"];
// sort() 默认按字母顺序(Unicode 顺序)排序
fruits.sort();
console.log(fruits);
// 输出: ["apple", "banana", "coconut", "orange", "pineapple"]
// ✅ 适用于字符串排序(默认升序)sort number
// ======================== 2️⃣ 数字排序(默认行为) ========================
// 定义一个数字数组
let numbers = [1, 10, 5, 6, 8, 2, 4, 9, 3, 7];
// 默认排序会将数字转换为字符串进行比较
numbers.sort();
console.log(numbers);
// 输出: [1, 10, 2, 3, 4, 5, 6, 7, 8, 9]
// ❌ 因为字符串比较是按第一个字符的 Unicode 编码排序
// "10" 的 "1" 在 "2" 前面,所以结果错误
// ======================== 3️⃣ 数字升序排列(自定义比较函数) ========================
// sort() 可以传入一个比较函数 compare(a, b)
// 如果返回值 < 0 → a 在前
// 如果返回值 > 0 → b 在前
// 如果返回值 = 0 → 保持原顺序
numbers.sort((a, b) => a - b);
console.log(numbers);
// 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// ✅ 数字正确升序排序
// ======================== 4️⃣ 数字降序排列 ========================
// 只需交换 a 和 b 的顺序(b - a)
numbers.sort((a, b) => b - a);
console.log(numbers);
// 输出: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
// ✅ 数字正确降序排序sort object
// ======================== 5️⃣ 对象数组排序(按数字属性) ========================
// 定义一个包含对象的数组,每个对象都有 name、age、gpa 三个属性
const people = [
{name: "Spongebob", age: 30, gpa: 3.0},
{name: "patrik", age: 37, gpa: 1.5},
{name: "squidward", age: 51, gpa: 2.5},
{name: "sandy", age: 27, gpa: 4.0},
];
// 按 age 从小到大排序
people.sort((a, b) => a.age - b.age);
console.log(people);
/*
输出:
[
{name: "sandy", age: 27, gpa: 4.0},
{name: "Spongebob", age: 30, gpa: 3.0},
{name: "patrik", age: 37, gpa: 1.5},
{name: "squidward", age: 51, gpa: 2.5}
]
*/
// ======================== 6️⃣ 对象数组排序(按 GPA 从低到高) ========================
// 比较对象中的 gpa 属性
people.sort((a, b) => a.gpa - b.gpa);
console.log(people);
/*
输出:
[
{name: "patrik", age: 37, gpa: 1.5},
{name: "squidward", age: 51, gpa: 2.5},
{name: "Spongebob", age: 30, gpa: 3.0},
{name: "sandy", age: 27, gpa: 4.0}
]
*/
// ======================== 7️⃣ 对象数组排序(按名字字母顺序) ========================
// localeCompare() 是字符串比较函数
// - 返回负数 → a 在 b 前
// - 返回正数 → a 在 b 后
// - 返回 0 → 相等
// 这个方法支持多语言(更智能的字母排序)
people.sort((a, b) => a.name.localeCompare(b.name));
console.log(people);
/*
输出:
[
{name: "patrik", age: 37, gpa: 1.5},
{name: "sandy", age: 27, gpa: 4.0},
{name: "squidward", age: 51, gpa: 2.5},
{name: "Spongebob", age: 30, gpa: 3.0}
]
*/
// ✅ 按名字首字母升序排列(字母顺序)