开发中经常遇到对数组排序的问题,一般有两种方式排序一种是for循环另外一种是利用数组内置的方法sort,其中sort不仅适用于简单的数组类型排序,也适用于复杂的数据类型排序。
①简单数组类型排序
let arrR=[1,8,6,9,3,6]
console.log(arrR.sort());//默认升序 [ 1, 3, 6, 6, 8, 9 ]
console.log(arrR.sort((a,b)=>b-a));//降序 [ 9, 8, 6, 6, 3, 1 ]
console.log(arrR.sort((a,b)=>a-b));//升序 [ 1, 3, 6, 6, 8, 9 ]
②复杂数组类型排序
let tableDate=[
{name:"xiaoming",age:23,dateTime:'2000-08-09 10:56'},
{name:"xiaolan",age:22,dateTime:'2001-06-09 11:36'},
{name:"xiaodu",age:24,dateTime:'1999-11-19 01:36'},
{name:"xiaohong",age:25,dateTime:'1998-12-09 06:36'},
{name:"xiaoxia",age:21,dateTime:'2002-03-09 16:36'},
{name:"xiaoliu",age:23,dateTime:'2000-07-09 18:36'}
]
tableDate.forEach(item=>{
item.dueDate=Date.parse(item.dateTime)
})
tableDate.sort((a,b)=>{
return a.dueDate-b.dueDate
})
console.log(tableDate);