【发布时间】:2020-03-31 03:51:01
【问题描述】:
我正在尝试编写一个函数来对这样的数组进行排序:
[
{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}
]
但我发现很难访问密钥(使用分数对每个对象进行排序并添加排名)。有人可以给我一些提示来编写这样的函数吗?
【问题讨论】:
-
如果您在使用库进行排序时没有任何问题,我建议您使用 lodash (lodash.com) _orderBy 方法按分数对数组进行排序,然后使用带有索引的 es6 map 函数添加您的行列。
-
首先以所需的方式对其进行排序并再次迭代数组以设置其排名
标签: javascript arrays reactjs