1.原生sort和reverse
sort()是按照升序排序的。sort会在每一项调用String(),默认排序顺序是在将元素转换为字符串,然后比较它们的UTF-16代码单元值序列时构建的。
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// [1, 100000, 21, 30, 4]
对于汉字也是把字符串转成了UTF-16构建。
const test = ["安张","安安","陈","北京"];
console.log(test.sort());
//[ ‘北京‘, ‘安安‘, ‘安张‘, ‘陈‘ ]
2.使用特定的排序规则
可以往sort传入一个比较函数,compare(a,b)<0,a会排在b之前(原生sort是从小到大排序的)
(1)按数字大小排序
const num = [12,100,91,83,84,97,21]
console.log(num.sort());
//如果只是比较数字而不非字符串
num.sort((a,b) => a-b)
console.log(num);
(2)按数组对象中的某个属性排序
按照水果的数量进行排序
const fruits = [
{
id:1,
status:0,
amount:11,
name:"西瓜"
},
{
id:2,
status:0,
amount:1,
name:"葡萄"
},
{
id:3,
status:1,
amount:11,
name:"梨子"
},
{
id:4,
status:0,
amount:22,
name:"苹果"
},
{
id:5,
status:1,
amount:4,
name:"提子"
}
];
fruits.sort((a,b) => {
return a.amount-b.amount;
})
console.log(fruits);
[
{ id: 2, status: 0, amount: 1, name: ‘葡萄‘ },
{ id: 5, status: 1, amount: 4, name: ‘提子‘ },
{ id: 1, status: 0, amount: 11, name: ‘西瓜‘ },
{ id: 3, status: 1, amount: 11, name: ‘梨子‘ },
{ id: 4, status: 0, amount: 22, name: ‘苹果‘ }
]
汉字拼音顺序排序
当排序非 ASCII 字符的字符串,比如按汉字拼音顺序排序,需要使用 String.localeCompare(),该方法返回一个数字来指示一个参考字符串是否在排序顺序前面或之后或与给定字符串相同。(和sort 传入compare方法一样的)
referenceStr.localeCompare(compareString[, locales[, options]])
locales和options使用的时候具体看文档
fruits.sort((a,b) => {
return a.name.localeCompare(b.name, ‘zh-Hans-CN‘, {sensitivity: ‘accent‘});
})
[
{ id: 3, status: 1, amount: 11, name: ‘梨子‘ },
{ id: 4, status: 0, amount: 22, name: ‘苹果‘ },
{ id: 5, status: 1, amount: 4, name: ‘提子‘ },
{ id: 1, status: 0, amount: 11, name: ‘西瓜‘ },
{ id: 2, status: 0, amount: 1, name: ‘枣‘ }
]
(3)多个优先级影响因素排序
1.status是水果的出售状态(第一优先级),amout是水果数量(第二优先级),name(第三优先级)
实际上不要写多个compare方法,只需要写if else 嵌套,把优先级高的放在前面
const fruits = [
{
id:1,
status:0,
amount:11,
name:"西瓜"
},
{
id:2,
status:0,
amount:1,
name:"枣"
},
{
id:3,
status:1,
amount:11,
name:"梨子"
},
{
id:4,
status:0,
amount:11,
name:"苹果"
},
{
id:5,
status:1,
amount:4,
name:"提子"
}
];
compare = (a,b) => {
if(a.status !== b.status){
return a.status-b.status ;
}else if(a.amount !== b.amount){
return a.amount-b.amount;
}else{
return a.name.localeCompare(b.name, ‘zh-Hans-CN‘, {sensitivity: ‘accent‘});
}
}
fruits.sort(compare);
console.log(fruits);
//排序结果
[
{ id: 2, status: 0, amount: 1, name: ‘枣‘ },
{ id: 4, status: 0, amount: 11, name: ‘苹果‘ },
{ id: 1, status: 0, amount: 11, name: ‘西瓜‘ },
{ id: 5, status: 1, amount: 4, name: ‘提子‘ },
{ id: 3, status: 1, amount: 11, name: ‘梨子‘ }
]