【问题标题】:How to sort an array of object using object's key? [duplicate]如何使用对象的键对对象数组进行排序? [复制]
【发布时间】: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


【解决方案1】:

您可以使用自定义sortArray.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);

【讨论】:

  • 当比较的 2 个值相同时,compareFunction 应该返回 0。应该是arr.sort((c1, c2) => c2.score - c1.score)
  • 当两个值相同时,排序顺序中的第一个并不重要。这就是为什么我没有处理那个案子。这有什么后果吗?我想知道。
  • 排序不会保持数组原有的相对顺序,会导致不同浏览器的结果不一致。
  • 好的,谢谢,我已经更新了我的答案:)
【解决方案2】:

您可以在一个衬里中使用排序和映射:

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; }

【讨论】:

    【解决方案3】:
    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}));
    

    【讨论】:

      猜你喜欢
      • 2020-05-18
      • 1970-01-01
      • 1970-01-01
      • 2013-02-24
      • 2020-07-11
      • 2021-12-09
      • 2022-01-20
      • 2017-02-15
      相关资源
      最近更新 更多