Sorting
Part of the REST APIs section of Coddy's Node.js journey. Lesson 16 of 25.
A client wants the newest tasks first, or the list from A to Z. A common convention is ?sort=field, with a - in front to reverse:
// GET /api/books?sort=-year
const field = sort.startsWith('-') ? sort.slice(1) : sort; // 'year'
const direction = sort.startsWith('-') ? -1 : 1;
list = list.toSorted((a, b) => (a[field] - b[field]) * direction);Check field against the fields you allow first and answer 400 for any other, since a field books do not have gives no useful order. toSorted returns a sorted copy. sort reorders the array itself, and when no filter made a copy, that array is the store: every later request sees the new order. This example subtracts, which works for numbers only. To compare two strings, use a.localeCompare(b): like the subtraction, it returns a negative number, 0 or a positive number. ISO dates are strings that sort in time order.
Challenge
EasyReplace the title-only sort you wrote in Sorting Text with the field and direction handling below.
Clients want the newest tasks first, or the list from A to Z. Let the list sort itself with ?sort=.
- In
routes/tasks.js, in the list route, readsortfromreq.query. Without it, the list keeps its stored order. ?sort=titlesorts by title from A to Z.?sort=createdAtsorts by creation time, oldest first. A-in front reverses the order:?sort=-titleis Z to A, and?sort=-createdAtis newest first.- Both fields are text.
createdAtis an ISO date like"2026-03-03T10:30:00.000Z", which sorts correctly as text. So compare withlocaleCompare, not by subtracting. - Any other field, like
?sort=color, gets status 400:{ "error": { "code": "invalid_query", "message": "sort must be title or createdAt, with - in front to reverse" } } - Sort after the filters, so
?done=false&sort=-titlereturns the open tasks from Z to A. - Sort a copy with
toSorted.sortreorders the stored array itself, and every later request would see the new order.
Try it: GET /api/tasks?sort=title returns tasks 2, 3, 1 ("Book...", "Send...", "Write..."). GET /api/tasks?sort=-createdAt returns 3, 2, 1. Then plain GET /api/tasks returns 1, 2, 3 again. GET /api/tasks?sort=color returns 400 with code invalid_query.
Try it yourself
import { Router } from 'express';
import { z } from 'zod';
import { sendError, sendInvalid } from '../errors.js';
import { nextId, tasks } from '../store.js';
const router = Router();
// A whole task, as PUT sends it. .strict() refuses fields it does not list.
const Task = z
.object({
title: z.string().trim().min(1).max(100),
done: z.boolean(),
})
.strict();
const NewTask = Task.partial({ done: true });
const TaskChanges = Task.partial();
// True when another task already has this title, in any case.
const titleTaken = (title, exceptId) =>
tasks.some((t) => t.id !== exceptId && t.title.toLowerCase() === title.toLowerCase());
router.get('/', (req, res) => {
const { done, q } = req.query;
let list = tasks;
if (done !== undefined) {
if (done !== 'true' && done !== 'false') {
return sendError(res, 400, 'invalid_query', 'done must be true or false');
}
list = list.filter((t) => t.done === (done === 'true'));
}
if (q !== undefined) {
const words = String(q).toLowerCase();
list = list.filter((t) => t.title.toLowerCase().includes(words));
}
if (req.query.sort === 'title') {
list = list.toSorted((a, b) => a.title.localeCompare(b.title));
}
res.json(list);
});
router.get('/:id', (req, res) => {
const task = tasks.find((t) => t.id === Number(req.params.id));
if (!task) {
return sendError(res, 404, 'not_found', 'Task not found');
}
res.json(task);
});
router.post('/', (req, res) => {
const result = NewTask.safeParse(req.body);
if (!result.success) {
return sendInvalid(res, result.error);
}
const { title, done = false } = result.data;
if (titleTaken(title)) {
return sendError(res, 409, 'conflict', 'A task with this title already exists');
}
const task = { id: nextId(), title, done, createdAt: new Date().toISOString() };
tasks.push(task);
res.status(201).location(`/api/tasks/${task.id}`).json(task);
});
router.patch('/:id', (req, res) => {
const task = tasks.find((t) => t.id === Number(req.params.id));
if (!task) {
return sendError(res, 404, 'not_found', 'Task not found');
}
const result = TaskChanges.safeParse(req.body);
if (!result.success) {
return sendInvalid(res, result.error);
}
if (result.data.title !== undefined && titleTaken(result.data.title, task.id)) {
return sendError(res, 409, 'conflict', 'A task with this title already exists');
}
Object.assign(task, result.data);
res.json(task);
});
router.put('/:id', (req, res) => {
const index = tasks.findIndex((t) => t.id === Number(req.params.id));
if (index === -1) {
return sendError(res, 404, 'not_found', 'Task not found');
}
const result = Task.safeParse(req.body);
if (!result.success) {
return sendInvalid(res, result.error);
}
const { id, createdAt } = tasks[index];
if (titleTaken(result.data.title, id)) {
return sendError(res, 409, 'conflict', 'A task with this title already exists');
}
tasks[index] = { id, ...result.data, createdAt };
res.json(tasks[index]);
});
router.delete('/:id', (req, res) => {
const index = tasks.findIndex((t) => t.id === Number(req.params.id));
if (index === -1) {
return sendError(res, 404, 'not_found', 'Task not found');
}
tasks.splice(index, 1);
res.status(204).end();
});
export default router;
All lessons in REST APIs
1Resources and Verbs
Resources and URLsCreating with POST4Browsers, Versions and Config
What Is an OriginAllowing Another OriginCORSA Page That Calls the APIPractice on your own: Express playground