js 数组重排序 sort 的用法
// 假如我们拿到一个没有排过序数组
// 我们需要根据数组中某个值来排序该怎么办
// 解决办法如下
let userInfo = [{
name: "张三",
age: 28
},
{
name: "李四",
age: 24
}, {
name: "王五",
age: 22
}, {
name: "孙毅",
age: 26
}, {
name: "江海",
age: 24
}, {
name: "江波",
age: 25
},
]
let newUserInfo = userInfo.sort((a, b) => {
return a.age - b.age;
});
console.log(JSON.stringify(newUserInfo));
// 输出 [{"name":"王五","age":22},{"name":"李四","age":24},{"name":"江海","age":24},{"name":"江波","age":25},{"name":"孙毅","age":26},{"name":"张三","age":28}]
// let newUserInfo = userInfo.sort((a, b) => {
// return b.age - a.age;
// });
// console.log(JSON.stringify(newUserInfo));
// 输出 [{"name":"张三","age":28},{"name":"孙毅","age":26},{"name":"江波","age":25},{"name":"李四","age":24},{"name":"江海","age":24},{"name":"王五","age":22}]