1、 修改数组中对象的排序
const arr = [
{id:1, is_must:true,},
{id:2, is_must:false,},
{id:3, is_must:false,},
{id:4, is_must:true,},
]
function reOrder(a,b) {
// reOrder:结果大于0:b在前,小于0:a在前
if(b.is_must==false && a.is_must==true){
return -1
}else{
return 1
}
}
const newArr = arr.sort(reOrder)
console.log(newArr)
// [
// {id:1, is_must:true,},
// {id:4, is_must:true,},
// {id:2, is_must:false,},
// {id:3, is_must:false,},
// ]
2、 修改数组中数值的排序
list:["100","24","489","22","307","6"];
sortNumber(a,b){
return a-b //从小到大排列;大于0:b在前,小于0:a在前
};
list.sort(sortNumber)
//["6", "22", "24", "100", "307", "489"]
3、修改数组中字符串的排序
list:["George","John","Thomas","James","Adrew","Martin"];
list.sort();
//["Adrew", "George", "James", "John", "Martin", "Thomas"]
4、修改时间字符串排序
list:["2024-04-10 17:00:57","2024-04-11 17:00:57","2024-04-9 17:00:57"];
function reOrder(a,b) {
// reOrder:从大到小排列;结果大于0:b在前,小于0:a在前
const date1 = new Date(a);
const date2 = new Date(b);
if(date1 > date2){
return -1
}else{
return 1
}
}
const newArr = list.sort(reOrder)
console.log('newArr',newArr)
//["2024-04-11 17:00:57","2024-04-10 17:00:57","2024-04-9 17:00:57"]