# Js sort()核心用法，有了它，你无需再为数组排序而发愁

### 定义和用法

sort() 方法用于对数组的元素进行排序（常规数组、对象数组）。

### 基本使用

1、对常规字符串数组进行排序（默认排序）：

``````var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
console.log(fruits,'=> fruits')``````

2、对常规数字数组进行排序（默认排序） ：

``````var numbers = [8,3,5,7,2,6];
numbers.sort();
console.log(numbers,'=> numbers')``````

``````var numbers = [8,13,5,7,20,6,1];
numbers.sort();
console.log(numbers,'=> numbers')``````

``````var minx = [8,13,5,7,0,20,6,1,"Banana", "Orange", "Apple", "Mango"];
minx.sort();
console.log(minx,'=> numbers and fruits')``````

3、实现自定义升序和降序

3.1、升序

``````var numbers = [8,13,5,7,20,6,1,6];
numbers.sort((a,b)=>{
if(a > b) {
return 1
}else if(a < b) {
return -1
}else if(a == b){
return 0
}
});
console.log(numbers,'=> numbers')``````

``````var numbers = [8,13,5,7,20,6,1,6];
numbers.sort((a,b)=>{
return a - b
});
console.log(numbers,'=> numbers')``````

sort()里面的函数返回值如果大于0，则a、b交换位置；（数组原本位置为a在b的前面）

3.2、降序

tips：一个小知识点，对升序之后的数组使用reverse()方法，可以达到目的。

``````var numbers = [8,13,5,7,20,6,1,6];
numbers.sort((a,b)=>{
if(b > a) {   //如果b > a，交换a、b位置，大值在前面，函数返回 > 0
return 2    //返回大于0的数即可
}else if(b < a) {
return -1
}else if(a == b){
return 0
}
});
console.log(numbers,'=> numbers')``````

简写模式（常用方式）

``````var numbers = [8,13,5,7,20,6,1,6];
numbers.sort((a,b)=>{
return b - a
});
console.log(numbers,'=> numbers')``````

4、对象数组的升序和降序

4.1、假设有一个对象数组，里面有几个对象，属性包括姓名、年龄、成绩：

``````let personList = [
{name:'leo', age:18, score:88},
{name:'lion', age:16, score:66},
{name:'alex', age:28, score:99},
{name:'gao', age:25, score:68},
{name:'ggj', age:22, score:98}
]``````

``````let personList = [
{name:'leo', age:18, score:88},
{name:'lion', age:16, score:66},
{name:'alex', age:28, score:99},
{name:'gao', age:25, score:68},
{name:'ggj', age:22, score:98},
]

personList.sort((a,b)=>{
return a.age - b.age   //使用年龄进行比较
})
console.log(personList,'按年龄升序')``````

``````personList.sort((a,b)=>{
return b.age - a.age   //使用年龄进行比较
})
console.log(personList,'按年龄降序')``````

``````personList.sort((a,b)=>{
return a.score - b.score   //使用成绩进行比较
})
console.log(personList,'按成绩升序')

personList.sort((a,b)=>{
return b.score - a.score   //使用成绩进行比较
})
console.log(personList,'按成绩降序')``````

4.2、对象数组由多个属性共同决定升、降序

``````let personList = [
{name:'leo', age:18, score:88},
{name:'lion', age:16, score:68},
{name:'alex', age:28, score:68},
{name:'gao', age:25, score:68},
{name:'ggj', age:22, score:98},
]
personList.sort((a,b)=>{
if(a.score != b.score){
//成绩不同，按成绩降序
return b.score - a.score
}else {
//成绩相同，按年龄降序
return b.age - a.age
}
})
console.log(personList,'由成绩、年龄共同排序')``````

THE END