1

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.

2

1 Answer 1

1

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))
          );
    };
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, comment.body are in fact strings - should have caught that earlier. After using localeCompare I got a TypeError, which was fixed by forcing a.toString().localCompare(b)), only now I'm not accessing the body of the comment at any point, should I be adding comment.body to my sort?
@James there was a silly mistake in my original answer, I edited a few minutes ago, please have another look at it... Notice how I am destructuring the body and renaming it to a and b? I wasn't doing that before. There is no reason for you to perform a toString :-)
Thanks for the quick edit, @Josep. For some reasons I'm getting undefined errors now. Even this.dataset.linkid is returning undefined - does it have to do with the position of my e.preventDefault()?
Nope, that's definitely a different problem... If you are getting undefined on the linkid property of the dataset, that can only mean one thing: In the moment when the #sort_comments was clicked, that HTML element does not have the data-linkid attribute set on it... But that's a completely different problem.
Ok, I figured as much but was a little confused given that I had that info earlier. Thank you very much for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.