Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
How to sort an item which is inside an array by query params?

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 - enter image description here The highest price is 225000. So the sorting is not working here.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Arrays are sorted by alphabetical values by default. Use this instead:

arr.sort((a, b) => a-b);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!