Kerbol
Kerbol

Reputation: 706

JSON Sorting by Alphabetical Order

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,

Upvotes: 5

Views: 10241

Answers (3)

Maizied Hasan Majumder
Maizied Hasan Majumder

Reputation: 1053

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

Upvotes: 0

Yosvel Quintero
Yosvel Quintero

Reputation: 19070

As of your question "JSON Sorting by Alphabetical Order" you can first use Array.prototype.sort() to sort the array and than populate the output variable and also use the separator the way you want to show the names in the html.

Code:

const people = [{first_name: 'Don Molloy',category: 'academic'}, {first_name: 'Pat Quill',category: 'academic'}];
const separator = '<br>';

// Sort array of objects by first_name and populate the output with separator
const output = people
  .sort((a, b) => a.first_name.toLowerCase().localeCompare(b.first_name.toLowerCase()))
  .map(user => user.first_name)
  .join(separator);

console.log(people);
document.getElementById('output-people').innerHTML = output;
<p id="output-people"></p>

Upvotes: 2

prasanth
prasanth

Reputation: 22500

This not json Object .its a normal array Object.so remove the JSON.parse() .And change the output innerHTML dom like this myObj[0].first_name

Update:

For all first_name with sort .try this myObj.map(a=> a.first_name).sort().join(" and ")

var people;

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

people = people.sort((a,b)=> {
var a1 = a.first_name.toLowerCase();
var b1 = b.first_name.toLowerCase();
return a1<b1 ?-1:a1> b1? 1 :0;
})
console.log(people);

var myObj =people;
document.getElementById("output-people").innerHTML = myObj.map(a=> a.first_name).join(" and ")
<p id="output-people"></p>

Upvotes: 9

Related Questions