How to Implement Sorting in Express API Easily
To implement sorting in an
Express API, accept a query parameter like sort in the request URL, then use JavaScript's Array.prototype.sort() on your data before sending the response. This lets clients specify the field and order (e.g., ascending or descending) to sort the results dynamically.Syntax
Use query parameters to get sorting instructions from the client, then apply Array.prototype.sort() on your data array.
req.query.sort: The field name to sort by, optionally prefixed with-for descending order.array.sort(): JavaScript method to reorder array elements.
javascript
app.get('/items', (req, res) => { const sortField = req.query.sort; // e.g. 'name' or '-price' let items = [...]; // your data array if (sortField) { const order = sortField.startsWith('-') ? -1 : 1; const field = sortField.startsWith('-') ? sortField.slice(1) : sortField; items.sort((a, b) => { if (a[field] < b[field]) return -1 * order; if (a[field] > b[field]) return 1 * order; return 0; }); } res.json(items); });
Example
This example shows an Express API endpoint /products that returns a list of products sorted by a query parameter sort. Prefix the field with - for descending order.
javascript
import express from 'express'; const app = express(); const products = [ { id: 1, name: 'Apple', price: 100 }, { id: 2, name: 'Banana', price: 50 }, { id: 3, name: 'Cherry', price: 75 } ]; app.get('/products', (req, res) => { const sortField = req.query.sort; let sortedProducts = [...products]; if (sortField) { const order = sortField.startsWith('-') ? -1 : 1; const field = sortField.startsWith('-') ? sortField.slice(1) : sortField; sortedProducts.sort((a, b) => { if (a[field] < b[field]) return -1 * order; if (a[field] > b[field]) return 1 * order; return 0; }); } res.json(sortedProducts); }); app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Output
GET /products?sort=price
[
{ "id": 2, "name": "Banana", "price": 50 },
{ "id": 3, "name": "Cherry", "price": 75 },
{ "id": 1, "name": "Apple", "price": 100 }
]
GET /products?sort=-name
[
{ "id": 3, "name": "Cherry", "price": 75 },
{ "id": 2, "name": "Banana", "price": 50 },
{ "id": 1, "name": "Apple", "price": 100 }
]
Common Pitfalls
Common mistakes when implementing sorting in Express APIs include:
- Not validating the
sortquery parameter, which can cause errors if the field does not exist. - Sorting data in place without copying, which can mutate shared data unexpectedly.
- Ignoring case sensitivity when sorting strings, leading to unexpected order.
- Not handling different data types (strings vs numbers) properly in the sort function.
javascript
/* Wrong: Sorting without checking field existence */ app.get('/items', (req, res) => { const sortField = req.query.sort; items.sort((a, b) => a[sortField] - b[sortField]); // fails if field missing or string res.json(items); }); /* Right: Validate field and handle strings/numbers */ app.get('/items', (req, res) => { const sortField = req.query.sort; const validFields = ['name', 'price']; if (sortField && validFields.includes(sortField.replace('-', ''))) { const order = sortField.startsWith('-') ? -1 : 1; const field = sortField.startsWith('-') ? sortField.slice(1) : sortField; items = [...items]; items.sort((a, b) => { const valA = a[field]; const valB = b[field]; if (typeof valA === 'string' && typeof valB === 'string') { return valA.localeCompare(valB) * order; } return (valA - valB) * order; }); } res.json(items); });
Quick Reference
- Use
req.query.sortto get sorting instructions. - Prefix field with
-for descending order. - Copy arrays before sorting to avoid side effects.
- Validate fields to prevent errors.
- Use
localeComparefor string sorting.
Key Takeaways
Use query parameters to let clients specify sorting fields and order.
Always validate the sorting field to avoid runtime errors.
Copy your data array before sorting to prevent unwanted mutations.
Handle string and number sorting differently for correct order.
Prefix the sort field with '-' to indicate descending order.