js 数组重排序 sort 的用法
程序员文章站
2024-02-23 08:01:04
...
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}]
上一篇: 同步上升/下降沿检测
下一篇: Verilog奇偶分频电路的总结