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的前面怎么弄
时间: 2023-12-20 13:04:12 浏览: 214
如果想要将`score`排到`age`的前面,可以先将数组对象中的`score`属性剔除出来,然后将剩余的属性进行排序,最后再将`score`属性插入到排序结果的前面。代码如下:
```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' },
];
const scores = arr.map(item => item.score); // 获取分数数组
const rest = arr.map(item => ({ name: item.name, age: item.age, grade: item.grade })); // 获取除分数外的其它属性
rest.sort((a, b) => {
if (a.age !== b.age) {
return a.age - b.age;
}
if (a.grade !== b.grade) {
return a.grade.localeCompare(b.grade);
}
return 0;
}); // 按照年龄升序、成绩等级升序排序
const result = rest.map((item, index) => ({ ...item, score: scores[index] })); // 组合成新的对象数组
console.log(result);
// 输出:[
// { name: '李四', age: 18, grade: 'B', score: 70 },
// { name: '赵六', age: 19, grade: 'A', score: 85 },
// { name: '张三', age: 20, grade: 'A', score: 80 },
// { name: '王五', age: 22, grade: 'A', score: 90 }
// ]
```
这里的排序规则是按照年龄升序、成绩等级升序排序,最后将分数属性插入到排序结果的前面,得到最终的排序结果。
阅读全文