1

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?

Devang Mukherjee
  • 185
  • 1
  • 1
  • 11

1 Answers1

1

You can sort it in the query itself. Try this

await Country.find({}, {'name': 1}).sort({name: 1})

Note: Inside sort, follow below values depending on result is required in which order.

1 Ascending
-1 Descending
Shreeram K
  • 1,719
  • 13
  • 22