我正在尝试编写一个对数组进行排序的函数:
[
{score:10, name:foo},
{score:-10, name:bar},
{score:0, name:newNAME}
]
进入
[
{rank:1, score:10, name:foo},
{rank:2, score:0, name:newNAME},
{rank:3, score:-10, name:bar}
]
但是我发现很难访问键(使用分数排序并在每个对象中添加等级)。有人可以给我一些编写此类功能的提示吗?
答案 0 :(得分:5)
您可以使用自定义的sort
和Array.prototype.map
向对象数组添加额外的键等级。
let arr = [{
score: 10,
name: "foo"
}, {
score: -10,
name: "bar"
}, {
score: 0,
name: "newNAME"
}];
arr.sort((c1, c2) => {
return c2.score - c1.score;
});
arr = arr.map((val, index) => {
val.rank = index + 1;
return val;
})
console.log(arr);
答案 1 :(得分:1)
您可以在一个衬里中使用排序和映射:
const sorted = [
{score: 10, name: "foo"},
{score: -10, name: "bar"},
{score: 0, name: "newNAME"} ]
.sort( (a, b) => a.score - b.score)
.map( (v, i) => ({rank: i + 1, ...v}));
console.log(sorted);
.as-console-wrapper { top: 0; max-height: 100% !important; }
答案 2 :(得分:0)
const sorted = [
{score: 10, name: "foo"},
{score: -10, name: "bar"},
{score: 0, name: "newNAME"} ]
.sort( (a, b) => a.score - b.score)
.map( (v, i) => ({rank: i + 1, ...v}));