【问题标题】:Sort an array of objects by property of second element in javascript [duplicate]按javascript中第二个元素的属性对对象数组进行排序[重复]
【发布时间】:2020-07-07 14:05:36
【问题描述】:

搜索了许多我没有设法解决我的案例的例子。我有一个数组 应该按author 排序。我的尝试什么也没做。什么是正确的表达方式?

var array = [
  ["ifke", {
    "title": "secure",
    "author": "admin"
  }],
  ["lottery", {
    "title": "The lo",
    "author": "anton"
  }],
  ["short-content", {
    "title": "Short Content",
    "author": "scott"

  }],
  ["ziddler", {
    "title": "The Fiddler",
    "author": "herman"

  }]
];


array.sort((a, b) => a[1].author - b[1].author)
console.log(array)

【问题讨论】:

  • 好吧,在尝试回答之前,我可以问一下为什么您的数据是这样构造的吗?太可怕了。因为如果这不仅仅是家庭作业,那么我强烈建议您重新考虑存储数据的方式
  • 试试array.sort((a, b) => a[1].author.localeCompare(b[1].author))
  • 感谢您的建议。数据结构来自 [import function loading markdown files into a JSON] (npmjs.com/package/markdown-to-json) 对象。现在我的目标是按照描述返回这个排序。

标签: javascript sorting


【解决方案1】:

您的想法是正确的,但您需要使用不同的比较方式。非数字字符串的减法运算符总是产生NaN,这对于比较是没有用的。

您可以使用localeCompare,它返回10-1

array.sort((a, b) => a[1].author.localeCompare(b[1].author))

【讨论】:

  • 欺骗............
【解决方案2】:

使用数组的 .sort 方法并使用 localeCompare 方法根据字符串进行排序的工作解决方案

var array = [
 [ "ifke", {
    "title": "secure",
    "author": "admin"
  }],
  ["lottery", {
    "title": "The lo",
    "author": "anton"
  }],
  ["short-content", {
    "title": "Short Content",
    "author": "scott"
  
  }],
  ["ziddler", {
    "title": "The Fiddler",
    "author": "herman"

  }]
];

array.sort((a,b) => a[1].author.localeCompare(b[1].author));
console.log(array);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    • 2012-03-13
    • 2017-05-31
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    相关资源
    最近更新 更多