繁体   English   中英

按属性对 JavaScript 对象进行排序

[英]Sort JavaScript Object by Attribute

我正在尝试按“正文”属性对一组评论对象进行排序。

我正在尝试运行以下命令(console.log(comment) 成功地显示了数组)但是当我对其进行排序时,我只是得到了相同的数组 - 即使在将其定义为sortedArray变量之后也是sortedArray

我见过一些类似的问题,但与我试图实现的箭头函数语法并不完全相同。

下面是我的代码:

function sortComments() {
  $("#sort_comments").on("click", function(e) {
    e.preventDefault();
    var id = this.dataset.linkid
    fetch(`/links/${id}/comments.json`)
      .then(r => r.json())
      .then(comments =>
        comments.sort(function(a, b) {
          return a.body - b.body;
        })
      );
  });
}

感谢您的帮助。

这里可能发生的是body属性是字符串而不是数字,因此减法的结果返回NaN ,如果是这种情况, Array的顺序不会改变。

为了比较 2 个不同的字符串,您可能需要使用localeCompare ,如下所示:

function sortComments() {
    $("#sort_comments").on("click", function (e) {
        e.preventDefault();
        var id = this.dataset.linkid
        fetch(`/links/${id}/comments.json`)
          .then(r => r.json())
          .then(comments => 
             comments.sort(({body: a}, {body: b}) => a.localeCompare(b))
          );
    };
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM