Start learning free

LESSON 28 OF 173 · BACKEND: YOUR FIRST API

Sort the List

Practice

Clients often want a list in a useful order: the cheapest products first, or names from A to Z. JavaScript's sort puts an array in order. It can't compare two objects by itself, though, so you give it a compare function: a function that takes two items, a and b, and returns a number. A negative number means a comes first, a positive one means b comes first.

function byStars(a, b) {
  return a.stars - b.stars;
}

const reviews = [{ user: "ana", stars: 5 }, { user: "bo", stars: 3 }];
reviews.sort(byStars);
// [{ user: "bo", stars: 3 }, { user: "ana", stars: 5 }]

Write byStars without parentheses: you hand over the function itself, and sort calls it on pairs of items. sort changes the order of the array it is called on, so sort a new array when the original must keep its order. Text can't be subtracted: a.localeCompare(b) compares two strings in alphabetical order and gives a negative number when a comes first.

The client picks the order with a query parameter: ?sort=price or ?sort=name. Any other value is a mistake, so the shop answers 400 with an error. Without sort, the list keeps the shop's order, and the filters still work. The lists below show product names only; each item is a full product.

GET /products?sort=price  →  200  [Pen, Notebook, Mug, Lamp]
GET /products?sort=name  →  200  [Lamp, Mug, Notebook, Pen]
GET /products  →  200  [Mug, Notebook, Lamp, Pen]
GET /products?category=office&sort=price  →  200  [Pen, Notebook]
GET /products?sort=color  →  400  {"error": "Sort must be price or name"}

Your task: write two compare functions, byPrice and byName. In GET /products, read sort, answer 400 for an unknown sort, and sort the filtered list by price or by name.


Assignment
Follow the Coding Tutorial to add sorting to GET /products.


Hint
Sort after the filter loop, so only the products that passed the filters get sorted. Give sort the compare function by its name, without parentheses.


STEP 1 OF 11
    Ctrl + Enter to check