0

I am trying to read data from a JSON file and display it alphabetically. I am getting results but not alphabetically? I am not sure what has gone wrong here.

$.getJSON("data.json", function(data) {
  var user_Data = "";

  var sorted = data.sort(function(a, b) {
    if (name.a > name.b) {
      return 1;
    }

    if (name.a < name.b) {
      return -1;
    }

    return 0;
  });

  $.each(sorted, function(key, value) {
    user_Data += '<p class="user col-md-6">' + value.name + '</p>';
  });
  $("#usernames").append("(" + data.length + ")"); //returns the total amount of contacts
  $("#usernames").append(user_Data);
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Your `sort()` logic seems flawed; `a` and `b` are references to the objects to be sorted, yet you're using them as property accessors? It would be helpful to see a small example of `data.json`. – Rory McCrossan Dec 04 '18 at 15:48
  • Also, don't reinvent the wheel. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare – Taplar Dec 04 '18 at 15:55
  • Have a look at below links : https://stackoverflow.com/questions/6712034/sort-array-by-firstname-alphabetically-in-javascript – Md Rana Hossain Dec 04 '18 at 17:20

1 Answers1

0

You are using wrong the objects of the array while sorting

var sorted = data.sort(function(a, b) {
    if (a.name > b.name) {
      return 1;
    }

    if (a.name < b.name) {
      return -1;
    }

    return 0;
  });

so name.a and name.b should really be a.name and b.name

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317