按javascript中第二个元素的属性对对象数组进行排序

时间:2020-07-07 14:05:36

标签: javascript sorting

搜索许多我无法解决的案例。我有一个数组 应该按- { routePath: '/news/{news-title}', _controller: 'News::detail', _arguments: {'news-title': 'news'}} - { routePath: '/{news-title}', _controller: 'News::detail', _arguments: {'news-title': 'news'}} 排序。我的尝试无济于事。正确的表达方式是什么?

author

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:2)

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

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

array.sort((a, b) => a[1].author.localeCompare(b[1].author))
相关问题