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.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
James
  • 411
  • 1
  • 4
  • 18

1 Answers1

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))
          );
    };
}
Josep
  • 12,926
  • 2
  • 42
  • 45
  • 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 Jan 29 '19 at 23:34
  • @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` :-) – Josep Jan 29 '19 at 23:36
  • 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()`? – James Jan 29 '19 at 23:41
  • 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. – Josep Jan 29 '19 at 23:47
  • Ok, I figured as much but was a little confused given that I had that info earlier. Thank you very much for your help! – James Jan 29 '19 at 23:48