I am learning Express.js. I am trying to sort these services by price. All the services are inside an array. Firstly I am filtering the items by their name which is working fine but when I am trying to sort them by their price it isn't working. Here's my code for sorting -
const getCategory = async (req, res) => {
let query;
const reqQuery = { ...req.query };
console.log(req.query);
if (req.query.name) {
query = Category.find(reqQuery);
} else {
query = Category.find();
}
if (req.query.sort) {
const sortByArr = req.query.sort.split(',').join(' ');
query = query.sort(sortByArr);
}
try {
const categories = await query.populate('services');
res.status(200).json({
message: 'All Category',
result: categories,
});
} catch (error) {
res.status(500).json({ message: error.message });
}
};
Here's the screenshot of my query in postman -
The highest price is 225000. So the sorting is not working here.
Arrays are sorted by alphabetical values by default. Use this instead:
arr.sort((a, b) => a-b);