简体   繁体   中英

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.

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.

In order to compare 2 different strings you probably want to use localeCompare , like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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