JS数组排序

本文介绍了JavaScript中数组的排序方法,包括常规数组的排序,强调了sort()方法在默认情况下按字符编码排序,需要提供比较函数来实现数值排序。此外,还讲解了对象数组的排序,如何根据对象的特定属性进行排序,并解决了在属性为字符串时排序失效的问题,以及如何实现更灵活的对象数组排序策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、常规数组排序

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}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值