Sub topic 7
Ranking and sorting results
This chapter assumes you have read the earlier chapters on search input and results presentation. You should be comfortable with TypeScript and basic HTML, and know what a results list and a filter are.
Ranking and sorting are different jobs
Ranking and sorting both put results in an order, but they answer different questions.
- Ranking orders results by estimated relevance to the query. The system decides the order, and the user usually cannot see why.
- Sorting orders results by a field the user picks, such as price, date, or rating. The user decides the order, and the rule is visible.
The two interact. When a user picks "Price: low to high," they override relevance. A cheap but unrelated item can then rise to the top. Your design has to decide how much of the query's relevance survives that choice.
| Aspect | Ranking | Sorting |
|---|---|---|
| Who controls it | The system | The user |
| Basis | Relevance signals | One field |
| Visible rule | Rarely | Always |
| Good default for | Text queries | Browsing and comparison |
| Main risk | Opaque, surprising order | Irrelevant items at the top |
What a ranking uses
A ranking function combines signals into one score. Common signals include:
- Text match: whether the query words appear, and where. A match in the title usually counts for more than a match in the description.
- Match quality: exact phrase, prefix match, or typo-corrected match.
- Popularity: sales, clicks, or views.
- Freshness: how recent the item is. This matters for news and listings, and matters little for stable catalogs.
- Quality: ratings, completeness of the item's data, or whether it is in stock.
- Personalization: the user's location, language, or past behavior.
Keep the first version simple. A weighted sum of a few signals is easy to explain and to debug.
type Item = {
id: string;
title: string;
description: string;
popularity: number; // 0 to 1
inStock: boolean;
};
function scoreItem(item: Item, query: string): number {
const q = query.trim().toLowerCase();
if (!q) return 0;
const title = item.title.toLowerCase();
const description = item.description.toLowerCase();
let score = 0;
if (title === q) score += 10;
else if (title.startsWith(q)) score += 6;
else if (title.includes(q)) score += 4;
if (description.includes(q)) score += 1;
score += item.popularity * 2;
if (!item.inStock) score -= 3;
return score;
}
function rank(items: Item[], query: string): Item[] {
return items
.map((item) => ({ item, score: scoreItem(item, query) }))
.filter((entry) => entry.score > 0)
.sort((a, b) => b.score - a.score || a.item.id.localeCompare(b.item.id))
.map((entry) => entry.item);
}
const catalog: Item[] = [
{ id: "1", title: "Trail boots", description: "Waterproof hiking boots", popularity: 0.9, inStock: true },
{ id: "2", title: "Boots polish", description: "Leather care", popularity: 0.4, inStock: true },
{ id: "3", title: "Rain boots", description: "Rubber boots", popularity: 0.7, inStock: false },
];
console.log(rank(catalog, "boots").map((i) => i.title));Three details in this code matter in practice.
- Text match dominates. Popularity can break ties and nudge order, but it cannot lift an irrelevant item above a good match.
- Out-of-stock items are demoted, not removed. Removing them hides information, and some users want to know the item exists.
- The sort has a tie-breaker (
id). Without one, equal scores can swap places between requests, and the list appears to shuffle.
Sorting options users need
Offer sort options that match the decisions users make in your domain. A short list works better than a long one.
- Relevance. Show it as the default whenever there is a text query.
- Price, low to high and high to low, for shopping.
- Newest, for listings, feeds, and documents.
- Rating or most reviewed, when quality varies.
- Distance, when location matters.
- Alphabetical, for directories and file lists.
When there is no query, such as when users browse a category, relevance has no meaning. Choose a default that fits the context, such as "Featured," "Popular," or "Newest." Hide the "Relevance" option in that case, or the user will select something that does nothing.
Control design
Use a single-choice control for sorting: a select menu, a dropdown button, or a segmented control for two or three options. Do not use checkboxes, because a list has exactly one order at a time.
State the current sort in the control's label, for example "Sort by: Price, low to high." The label should name the direction in words. An arrow icon alone is unclear.
Ranking versus sorting in practice
Sort is a stable, predictable order
When the user sorts by a field, many items will share the same value. Rating of 4.5 is a common case. Define a secondary order, and make it relevance when a query exists. That way "Price: low to high" with the query "boots" shows boots first among items at the same price.
type Result = { id: string; price: number; relevance: number };
function sortByPrice(results: Result[], direction: "asc" | "desc"): Result[] {
const sign = direction === "asc" ? 1 : -1;
return [...results].sort(
(a, b) =>
sign * (a.price - b.price) ||
b.relevance - a.relevance ||
a.id.localeCompare(b.id)
);
}
const sample: Result[] = [
{ id: "a", price: 20, relevance: 3 },
{ id: "b", price: 20, relevance: 9 },
{ id: "c", price: 10, relevance: 1 },
];
console.log(sortByPrice(sample, "asc").map((r) => r.id)); // ["c", "b", "a"]Missing values need a rule
Some items lack the sort field. A product may have no rating, or a listing may have no price. Decide where they go. Placing them last in both directions is the usual choice, because it keeps the useful items first. Do not treat a missing price as zero, or those items will lead the "low to high" list.
Sort changes the page, not the query
Changing the sort should keep the query and all filters. It should reset pagination to the first page, because page 3 of the old order has no meaning in the new order. Keep the sort in the URL, as covered in the chapter on filter state.
Showing why results appear in this order
Users trust an order they can understand. You can build trust without exposing the formula.
- Highlight the matched words in titles and snippets.
- Label special placements, such as "Sponsored" or "Featured." Mark them clearly and consistently. Mixing paid placements into the list without a label damages trust and may break advertising rules.
- Show the active sort in the interface, near the result count.
- Where relevance is the sort, say so in the control, for example "Sort by: Best match."
<div class="results-toolbar">
<p role="status">24 results for "boots"</p>
<label for="sort">Sort by</label>
<select id="sort" name="sort">
<option value="relevance" selected>Best match</option>
<option value="price_asc">Price: low to high</option>
<option value="price_desc">Price: high to low</option>
<option value="newest">Newest</option>
</select>
</div>Order that changes while the user looks
Results can reorder because new data arrives, a filter changes, or a live score updates. A list that moves under the user's cursor causes mis-clicks and loses their place.
- Do not reorder a visible list on a timer. Show a prompt such as "New results available" and let the user apply it.
- When the user changes a filter or sort, reorder, but move focus and scroll position back to the top of the list. Announce the change through the status message.
- Keep item positions stable while the user is interacting with an item.
Common errors
- Default sort is wrong for the context. A "Newest" default on a query page buries the best match. Default to relevance when there is a query.
- Sort silently drops the query's meaning. Items unrelated to the query appear first. Use relevance as the secondary key, and consider a relevance threshold.
- No tie-breaker. The same query returns shuffled results on each request, so users cannot find an item they saw a moment ago.
- Boosting hides good matches. A large popularity weight pushes popular but weak matches above exact matches. Test with known queries.
- Personalization with no escape. Users cannot tell why they see different results than a colleague. Offer a plain sort option, and avoid personalization that changes the order of core, factual results.
- Hidden sponsored items. Unlabeled paid placements look like relevance.
- Pagination after sort change. Staying on page 4 after the sort changes shows an arbitrary slice.
Choosing the right approach
Use these decision rules.
- If users type a query and want the best answer, rank by relevance and offer a few sorts as secondary tools.
- If users compare items on a clear attribute, such as price, put sort controls prominently and keep relevance as the tie-breaker.
- If the content is time-based, such as messages or logs, default to newest and make relevance an option.
- If your ranking is hard to explain, simplify it before adding more signals.
Exercise
A user searches for "boots" and then selects "Price: low to high." The first result is a bootlace costing 1 dollar, which has little to do with what they wanted. What two changes to the sort logic would improve this, and what must you also do when the sort changes?
Show answer
Use relevance as the secondary sort key so that items at the same price are ordered by match quality, and consider a relevance threshold so weak matches do not appear at all. When the sort changes, keep the query and filters, reset pagination to the first page, and update the URL and the status message.
Exercise
Your sort-by-rating list shows unrated products first when sorted from high to low. What is the likely cause, and what should the rule be?
Show answer
Missing ratings are being treated as a value such as zero or as sorting before real values. Missing values should be placed last in both directions, so items with real ratings come first.