方法一:冒泡排序
var arr1 = [{name:"小明",age:15},{name:"小芳",age:14},{name:"小复",age:19},{name:"小是",age:30}];
for(var i=0;i<arr1.length;i++){
for(var j=0;j<arr1.length;j++){
if(arr1[i].age>arr1[j].age){
var tem=arr1[i];
arr1[i]=arr1[j];
arr1[j]=tem;
}
}
}
console.log(arr1);
方法二:sort()方法排序
sort()方法默认按unicode编码顺序进行排序,因此需要传入回调函数进行比较排序
var arr1 = [{name:"小明",age:15},{name:"小芳",age:14},{name:"小复",age:19},{name:"小是",age:30}];
//根据用户的年龄进行排序
arr1.sort(function(a,b){
return a.age-b.age;
})
console.log(arr1);
方法三:快速排序(性能最好)
var arr=[];
for(var i=0;i<10000;i++){
var res = Math.floor(Math.random()*1000);
arr.push(res);
}
function quickOrder(arr){
var left = [];
var right = [];
if(arr.length<=1){
return arr;
}
var first = arr.splice(0,1);
for(var i=0;i<arr.length;i++){
if(first<arr[i]){
left.push(arr[i]);
}else{
right.push(arr[i]);
}
}
return quickOrder(left).concat(first,quickOrder(right));
}
console.log(quickOrder(arr));