一、常规数组排序
js中使用sort()方法可对数组进行排序。
如果调用sort()方法时没有使用参数,将按照字符编码的顺序进行排序。要实现这一点,首先应把数组的元素都转换成字符串(如有必要),以便进行比较。如果想按照其他标准进行排序,就需要提供比较函数,该函数要比较两个值,然后返回一个用于说明这两个值的相对顺序的数字。
示例:
var arr = [12,5,7,2,25];
console.log(arr.sort()); //[12, 2, 25, 5, 7]
输出结果为:
[12, 2, 25, 5, 7]
注意:上面的代码没有按照数值的大小对数字进行排序,要实现这一点,就必须使用一个排序函数
原因:sort方法会调用每个数组项的toString()方法,得到字符串,然后再对得到的字符串进行排序。虽然数值12比2大,但在进行字符串比较时"12"则排在"2"前面。此时,需要使用sort()方法的参数,这个参数即为比较函数。
使用比较函数,示例如下:
function sortNumber(a,b){
return a - b
}
var arr = [12,5,7,2,25];
console.log(arr);
console.log(arr.sort());
console.log(arr.sort(sortNumber));
aar: [12, 5, 7, 2, 25]
arr.sort(): [12, 2, 25, 5, 7]
arr.sort(sortNumber): [2, 5, 7, 12, 25]
二、对象数组排序
如果数组项是对象,需要根据数组项的某个属性对数组进行排序时,则和使用比较函数类似。
2.1 根据数组对象确定属性排序
示例:
var students = [
{id:1,name:'tom',score:12},
{id:3,name:'john',score:2},
{id:2,name:'lily',score:25}
];
对 students的成绩进行排序,此时需增加如下函数:
var compare_old = function (student1, student2) {
var val1 = student1.score;
var val2 = student2.score;
if (val1 < val2) {
return -1;
} else if (val1 > val2) {
return 1;
} else {
return 0;
}
}
console.log(students.sort(compare_old ));
打印结果:
0: {id: 3, name: "john", score: 2}
1: {id: 1, name: "tom", score: 12}
2: {id: 2, name: "lily", score: 25}
注意:若成绩是字符串时,此时排序会失效。如下
var students = [{id:1,name:'tom',score:'12'},{id:3,name:'john',score:'2'},{id:2,name:'lily',score:'25'}];
console.log(students.sort(compare));
打印结果:
0: {id: 1, name: "tom", score: "12"}
1: {id: 3, name: "john", score: "2"}
2: {id: 2, name: "lily", score: "25"}
此时应将字符串转换为数字再排序即可。
错误原因:两个数字字符串比较大小时,会比较它们的ASCII值大小,小的在前。比较规则是:从第一个字符开始,顺次向后直到出现不同的字符为止,然后以第一个不同的字符的ASCII值确定大小。
2.2 根据数组对象灵活排序
上述排序方法只可根据对象中的某一指定属性排序,如 students 中只可根据 score 属性排序,若也需根据 id 或者 name 排序该如何解决?改造 compare 方法即可。如下:
var students = [{id:1,name:'tom',score:12},{id:3,name:'john',score:2},{id:2,name:'lily',score:25}];
var compare_new = function (porp){
return function (student1, student2) {
var val1 = student1[porp];
var val2 = student2[porp];
if (val1 < val2) {
return -1;
} else if (val1 > val2) {
return 1;
} else {
return 0;
}
}
}
console.log(students.sort(compare_new ('name')));
打印结果:
0: {id: 3, name: "john", score: 2}
1: {id: 2, name: "lily", score: 25}
2: {id: 1, name: "tom", score: 12}
console.log(students.sort(compare_new ('id')));
打印结果:
0: {id: 1, name: "tom", score: 12}
1: {id: 2, name: "lily", score: 25}
2: {id: 3, name: "john", score: 2}