4-1升序
arr.sort((a,b)=>{
return a-b;
})
4-2降序
arr.sort((a,b)=>{
return b-a;
})
例子
实现数组的排序
var arr=[4,7,1,3,14];
//升序
arr.sort((a,b)=>{
return a-b;
})
console.log(arr);//[1,3,4,7,14]
//降序
arr.sort((a,b)=>{
return b-a;
})
console.log(arr);//[14,7,4,3,1]
实现数组中元素的排序
var students=[
{name:"zhang",age:20},
{name:"li",age:18},
{name:"wang",age:9},
{name:"陈",age:14},
]
//升序
var result=students.sort((a,b)=>{
return a["age"]-b["age"];
})
console.log(result);
//降序
var result=students.sort((a,b)=>{
return b["age"]-a["age"];
})
console.log(result);
实现指定条件排序
<button id="like">通过好评数排序</button>
<button id="price">通过价格排序</button>
<script>
var like=document.getElementById("like");
var price=document.getElementById("price");
var sales=[
{name:"张三",like:60,distance:1000,price:10},
{name:"张三",like:30,distance:100,price:40},
{name:"张三",like:20,distance:500,price:6},
]
//升序
function addOrder(arr,value){
var res=arr.sort((a,b)=>{
return a[value]-b[value];
})
return res;
}
like.onclick=function(){
console.log(addOrder(sales,"like"))
}
price.onclick=function(){
console.log(addOrder(sales,"price"))
}
</script>