简体   繁体   English

按属性对 JavaScript 对象进行排序

[英]Sort JavaScript Object by Attribute

I'm trying to sort an array of comment objects by their "body" attribute.我正在尝试按“正文”属性对一组评论对象进行排序。

I'm trying to run the following (console.log(comment) successfully shows the array) but when I go to sort it, I just get the same array back - even after defining it as a sortedArray variable.我正在尝试运行以下命令(console.log(comment) 成功地显示了数组)但是当我对其进行排序时,我只是得到了相同的数组 - 即使在将其定义为sortedArray变量之后也是sortedArray

I've seen some similar questions, but not quite with the arrow function syntax that I'm trying to implement.我见过一些类似的问题,但与我试图实现的箭头函数语法并不完全相同。

Below is my code:下面是我的代码:

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

Thank you for your help.感谢您的帮助。

What's probably happening here is that the body attribute is a string and not a number, therefore the result of that subtraction returns NaN , and if that's the case the order of the Array won't change.这里可能发生的是body属性是字符串而不是数字,因此减法的结果返回NaN ,如果是这种情况, Array的顺序不会改变。

In order to compare 2 different strings you probably want to use localeCompare , like this:为了比较 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