简体   繁体   中英

Sort json response of api alphabetically

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM