JS 数组 对象 字母排序
JavaScript中可以使用sort()方法对数组进行排序,也可以使用localeCompare()方法对字符串进行排序。
对于对象数组的排序,可以在sort()方法中传入一个比较函数,根据需要比较的属性进行排序。例如,对于以下对象数组:
const arr = [
{ name: "John", age: 25 },
{ name: "Mary", age: 30 },
{ name: "Bob", age: 20 }
];
可以按照年龄进行排序:
arr.sort((a, b) => a.age - b.age);
也可以按照名字进行排序:
arr.sort((a, b) => a.name.localeCompare(b.name));
注意,localeCompare()方法返回一个数字,如果字符串a应该排在字符串b前面,返回负数;如果字符串a应该排在字符串b后面,返回正数;如果两个字符串相等,返回0。
原文地址: https://www.cveoy.top/t/topic/cJZg 著作权归作者所有。请勿转载和采集!