<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js数组排序</title>
</head>
<body>
<script>
//数组中有多个数组,根据数组的某一列,对多个数组排序
var array1 = [
[1, 3, 6],
[3, 2, 1],
[4, 1, 5]
];
sort1(array1, 2); //根据数组的第二列进行排序
function sort1(array, index) {
array.sort(function (arr1, arr2) {
return arr1[index] - arr2[index]; //升序
//return arr2[index] - arr1[index]; //降序
});
}
//数组中有多个对象,根据对象的某个属性,对多个数组排序
var array2 = [
{"age": 18, "level": 5},
{"age": 15, "level": 7},
{"age": 20, "level": 4}
];
sort2(array2);
function sort2(array) {
array.sort(function (obj1, obj2) {
return obj1.age - obj2.age; //升序
//return obj2.age - obj1.age; //降序
});
}
</script>
</body>
</html>
js数组排序
最新推荐文章于 2022-04-01 16:34:49 发布