javascript怎么对数组对象里的4元素进行按我的要求任意排序案例const arr = [ { name: '张三', age: 20, score: 80, grade: 'A' }, { name: '李四', age: 18, score: 70, grade: 'B' }, { name: '王五', age: 22, score: 90, grade: 'A' }, { name: '赵六', age: 19, score: 85, grade: 'A' }, ];我想讲score排到age的前面怎么弄
时间: 2024-02-27 07:54:18 浏览: 118
如果想要将`score`排到`age`的前面,可以修改比较函数的实现,将`score`的比较放在`age`的前面。修改后的代码如下:
```javascript
const arr = [
{ name: '张三', age: 20, score: 80, grade: 'A' },
{ name: '李四', age: 18, score: 70, grade: 'B' },
{ name: '王五', age: 22, score: 90, grade: 'A' },
{ name: '赵六', age: 19, score: 85, grade: 'A' },
];
// 按照分数降序,年龄升序,成绩等级升序排序
arr.sort((a, b) => {
if (a.score !== b.score) {
return b.score - a.score;
}
if (a.age !== b.age) {
return a.age - b.age;
}
if (a.grade !== b.grade) {
return a.grade.localeCompare(b.grade);
}
return 0;
});
console.log(arr);
// 输出:[
// { name: '王五', age: 22, score: 90, grade: 'A' },
// { name: '赵六', age: 19, score: 85, grade: 'A' },
// { name: '张三', age: 20, score: 80, grade: 'A' },
// { name: '李四', age: 18, score: 70, grade: 'B' }
// ]
```
这里的排序规则是按照分数降序,年龄升序,成绩等级升序排序。首先比较分数,如果分数相同,再比较年龄,如果年龄相同,再比较成绩等级。这样,`score`就会排到`age`的前面。
阅读全文