通过数组的某一个属性值进行排序(如id)
1 let arr = [ 2 {id: 1, name: 'aaa'}, 3 {id: 4, name: 'ddd'}, 4 {id: 2, name: 'bbb'}, 5 {id: 3, name: 'ccc'} 6 ] 7 arr.sort((a, b) => { 8 return (a.id + '') > (b.id + '')? 1 : -1; 9 }) 10 console.log(arr) // 得到的即为通过id排序好的
console.log([{id: 1}, {id: 3}, {id: 2}].sort((a,b) => {return a.id - b.id}))
打印得到:
[{id:1}, {id:2},{id:3}]
希望大佬看到有不对的地方,提出博主予以改正!