JSON Sorting by Alphabetical Order

Viewed 6905

I am trying to output the JSON below to HTML. I have created the object along with the properties for this object however, I am struggling to output this to HTML. Here is what I have so far. Any idea?

var people;

people = [{
    first_name: 'Don Molloy',
    category: 'academic'
  },
  {
    first_name: 'Pat Quill',
    category: 'academic'
  }
];

console.log(people);

var myObj = JSON.parse(people);
document.getElementById("output-people").innerHTML = myObj.name;
<p id="output-people"></p>

thanks,

3 Answers

JSON Sorting by Alphabetical Order in JS =>

You can try this way:

function compareStrings(a, b) {
  // Assuming you want case-insensitive comparison
  a = a.toLowerCase();
  b = b.toLowerCase();

  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

places.sort(function(a, b) {
  return compareStrings(a.first_name, b.first_name);
})
Related