一个数组先按照某个属性的大小排序,如果大小一样的就按照名称排序
重写数组中的sort()方法
下面先以distance排序,如果相同以name排序
let arr = [
{distance: 3, name: 'jack'},
{distance: 1, name: 'tom'},
{distance: 5, name: 'abole'},
{distance: 8, name: 'jhon'},
{distance: 4, name: 'yasa'},
{distance: 4, name: 'tina'},
{distance: 4, name: 'bob'}
]
let sortBynum_name = (a, b) => {
if (a.distance - b.distance === 0) {
console.log(a, b)
return a.name.localeCompare(b.name);
}else {
return a.distance - b.distance;
}
}
arr.sort(sortBynum_name);
console.log(arr)
打印结果


浙公网安备 33010602011771号