CH *_* L 0 javascript arrays reactjs
我正在尝试编写一个函数来对这样的数组进行排序:
[
{score:10, name:foo},
{score:-10, name:bar},
{score:0, name:newNAME}
]
Run Code Online (Sandbox Code Playgroud)
进入
[
{rank:1, score:10, name:foo},
{rank:2, score:0, name:newNAME},
{rank:3, score:-10, name:bar}
]
Run Code Online (Sandbox Code Playgroud)
但是我发现很难访问密钥(使用分数对每个对象进行排序和添加排名)。有人可以给我一些提示来编写这样的函数吗?
您可以使用自定义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);Run Code Online (Sandbox Code Playgroud)