通过数组的某一个属性值进行排序(如id)

时间:2022-04-07 04:09:31
 let arr = [
{id: 1, name: 'aaa'},
{id: 4, name: 'ddd'},
{id: 2, name: 'bbb'},
{id: 3, name: 'ccc'}
]
arr.sort((a, b) => {
return (a.id + '') > (b.id + '')? 1 : -1;
})
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}]