I am trying to receive get api response in an alphabetically sorted order. I have tried the second answer from this question - Sort JSON response alphabetically using Javascript
My javascript code
function OrderListBy(prop) {
return function (a, b) {
if (a[prop] > b[prop]) {
return 1;
}
if (a[prop] < b[prop]) {
return -1;
}
return 0;
};
}
router.get('/countries', async (req, res) => {
try {
const countries = await Country.find({}, 'name');
const sortedCountries = countries.sort(OrderListBy('name'));
res.send(sortedCountries);
} catch (e) {
res.status(500).send();
}
});
OUTPUT
[
{
"_id": "5f0ccf5f45a1a51ca99382a3",
"name": "Australia"
},
{
"_id": "5eb6c2e94298400b6eb6ca3c",
"name": "India"
},
{
"_id": "5ec68ca5325d997b752056cd",
"name": "china"
}
]
it should return China before India alphabetically. Its returning the countries in order they created. This isn't working. What am I doing wrong?