sort() 方法用于对数组的元素进行排序,并返回数组。默认排序顺序是根据字符串Unicode码点。
array.sort(fun(a,b));
fun是个函数用来规定排序顺序。参数可有可无,无参数则按默认排序
不传参数,将不会按照数值大小排序,按照字符编码的顺序进行排序;
例1:
var arr = ['General','Tom','Bob','John','Army'];
var resArr = arr.sort();
console.log(resArr);
//输出 ["Army", "Bob", "General", "John", "Tom"]
例2:注意输出结果:并不是按照数值大小排序
var arr2 = [30,10,111,35,1899,50,45];
var resArr2 = arr2.sort();
console.log(resArr2);
//输出 [10, 111, 1899, 30, 35, 45, 50]
升序a-b
var arr3 = [30,10,111,35,1899,50,45];
arr3.sort(function(a,b){
return a - b;
})
console.log(arr3);
//输出 [10, 30, 35, 45, 50, 111, 1899]
降序b-a
var arr4 = [30,10,111,35,1899,50,45];
arr4.sort(function(a,b){
return b - a;
})
console.log(arr4);
//输出 [1899, 111, 50, 45, 35, 30, 10]
id升序,id相同条件下age降序
var arr6 = [
{id:10,age:2},
{id:5,age:4},
{id:6,age:10},
{id:9,age:6},
{id:2,age:8},
{id:10,age:9}];
arr6.sort(function(a,b){
if(a.id === b.id){//如果id相同,按照age的降序
return b.age - a.age
}else{
return a.id - b.id
}
})
console.log(arr6);
//输出新的排序
// {id: 2, age: 8}
// {id: 5, age: 4}
// {id: 6, age: 10}
// {id: 9, age: 6}
// {id: 10, age: 9}
// {id: 10, age: 2}
版本号大小排序
var data = {
"objects": [
{ "time": "2022-04-14 15:00",
"app_version": "2.12.110.540" },
{ "time": "2022-04-14 13:07",
"app_version": "2.7.1.528" },
{ "time": "2022-04-14 14:59",
"app_version": "2.12.90.536" }
]
}
data.objects.sort((a, b) => {
var a_ver_list = a["app_version"].split('.');
var b_ver_list = b["app_version"].split('.');
var first_diff_index = 0;
var arr_len = a_ver_list.length;
var comp_ret = 0;
for (; first_diff_index != arr_len; first_diff_index++){
if (a_ver_list[first_diff_index] != b_ver_list[first_diff_index]){
comp_ret = (parseInt(b_ver_list[first_diff_index], 10) - parseInt(a_ver_list[first_diff_index] ,10));
break;
}
}
return comp_ret;
});
输出结果:
"objects": [
{ "time": "2022-04-14 15:00",
"app_version": "2.12.110.540" },
{ "time": "2022-04-14 14:59",
"app_version": "2.12.90.536" },
{ "time": "2022-04-14 13:07",
"app_version": "2.7.1.528" }
]
参考链接:
https://blog.csdn.net/m0_37885651/article/details/80016718