Sub topic 7
Sorting rows
This chapter adds client-side sorting to the contact table from the earlier chapters. It then covers the cases where client-side sorting gives wrong or surprising results, and shows how to move the sort to the server.
It assumes you can build a basic lightning-datatable with a columns array and a key-field. It also assumes you can wire an Apex method to a component and handle events in LWC.
How sorting works in the datatable
lightning-datatable does not sort anything itself. It shows a clickable header with a sort arrow and fires an event. Your component has to reorder the rows and tell the table which column is sorted, so the arrow appears in the right place.
Three pieces make this work:
| Piece | Where | Purpose |
|---|---|---|
| `sortable: true` | Column definition | Makes the header clickable. |
| `onsort` | Template | Runs your handler when the user clicks a sortable header. |
| `sorted-by` and `sorted-direction` | Template | Show the arrow on the correct column, pointing up (`asc`) or down (`desc`). |
The sort event carries event.detail.fieldName and event.detail.sortDirection. The direction is either 'asc' or 'desc'. The table alternates the direction when the user clicks the same header again. It always starts with 'asc' when the user clicks a different column.
The basic handler
The columns in this example already have sortable: true on Name. To make the other columns sortable, add the same property to them.
<template>
<lightning-card title="Contacts" icon-name="standard:contact">
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
sorted-by={sortedBy}
sorted-direction={sortedDirection}
onsort={handleSort}
hide-checkbox-column>
</lightning-datatable>
</lightning-card>
</template>The handler reads the event detail, sorts, and stores the state:
sortedBy;
sortedDirection = 'asc';
handleSort(event) {
const { fieldName, sortDirection } = event.detail;
const factor = sortDirection === 'asc' ? 1 : -1;
this.data = [...this.data].sort((a, b) => {
const x = a[fieldName] ?? '';
const y = b[fieldName] ?? '';
return x > y ? factor : x < y ? -factor : 0;
});
this.sortedBy = fieldName;
this.sortedDirection = sortDirection;
}Two details matter here.
- Sort a copy. Data returned by a wire adapter is read-only. Calling
this.data.sort(...)directly on it throws an error or silently does nothing, depending on the runtime.[...this.data]creates a new array that you can reorder. - Assign a new array. The table re-renders because
this.datapoints at a new array. Sorting in place on an array you own would not trigger the update.
Improving the comparison
The handler above works for simple cases, but it has three weaknesses:
- It compares strings with
>and<, which uses UTF-16 code unit order. Every uppercase letter sorts before every lowercase letter, so"Zoe"comes before"adam". - Number-like strings sort as text, so
"10"comes before"9". - Empty values are turned into
'', so they sort first in ascending order and last in descending order. Users usually expect empty cells at the bottom either way.
A reusable function fixes all three. Intl.Collator compares strings in a locale-aware way, ignores case differences with sensitivity: 'base', and compares embedded digits as numbers with numeric: true.
import { LightningElement, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
const COLUMNS = [
{ label: 'Name', fieldName: 'Name', type: 'text', sortable: true },
{ label: 'Email', fieldName: 'Email', type: 'email', sortable: true },
{ label: 'Phone', fieldName: 'Phone', type: 'phone' },
{ label: 'Birthdate', fieldName: 'Birthdate', type: 'date-local', sortable: true }
];
const collator = new Intl.Collator(undefined, {
sensitivity: 'base',
numeric: true
});
const isEmpty = (value) =>
value === undefined || value === null || value === '';
function sortRows(rows, fieldName, direction) {
const factor = direction === 'asc' ? 1 : -1;
return [...rows].sort((a, b) => {
const x = a[fieldName];
const y = b[fieldName];
if (isEmpty(x) && isEmpty(y)) return 0;
if (isEmpty(x)) return 1;
if (isEmpty(y)) return -1;
if (typeof x === 'number' && typeof y === 'number') {
return (x - y) * factor;
}
return collator.compare(String(x), String(y)) * factor;
});
}
export default class ContactTable extends LightningElement {
columns = COLUMNS;
data = [];
error;
wiredResult;
sortedBy;
sortedDirection = 'asc';
@wire(getContacts)
wiredContacts(result) {
this.wiredResult = result;
const { data, error } = result;
if (data) {
this.data = this.sortedBy
? sortRows(data, this.sortedBy, this.sortedDirection)
: data;
this.error = undefined;
} else if (error) {
this.error = error;
this.data = [];
}
}
handleSort(event) {
const { fieldName, sortDirection } = event.detail;
this.data = sortRows(this.data, fieldName, sortDirection);
this.sortedBy = fieldName;
this.sortedDirection = sortDirection;
}
}The wire handler reapplies the current sort when new data arrives. Without that step, any refresh (for example refreshApex after an inline edit) replaces the rows with the server's order, while the header arrow still claims the table is sorted. The same applies to rows appended by infinite loading.
Empty values stay at the bottom in both directions because the empty checks run before the direction factor is applied.
Birthdate with type date-local arrives as an ISO string such as 2001-04-09. ISO dates sort correctly as strings, so the collator handles them. If a field is stored as a formatted string such as 04/09/2001, string sorting is wrong and you must parse the value first.
Common errors
The arrow shows on the wrong column, or not at all
sorted-by must equal the fieldName of the column, character for character. If you set sortedBy to the label ('Name' when the field is 'FullName'), no arrow appears. Take the value from event.detail.fieldName instead of typing it.
Sorting a column that uses a different field for display
Some column types take their visible text from typeAttributes. A url column, for example, can use fieldName: 'ProfileUrl' with typeAttributes: { label: { fieldName: 'Name' } }. The sort event reports ProfileUrl, not Name, so users would see rows sorted by link rather than by the visible text. Handle this by mapping the event's field name to the field you actually want to sort on:
const SORT_FIELD_BY_COLUMN = {
ProfileUrl: 'Name'
};
handleSort(event) {
const { fieldName, sortDirection } = event.detail;
const sortField = SORT_FIELD_BY_COLUMN[fieldName] ?? fieldName;
this.data = sortRows(this.data, sortField, sortDirection);
this.sortedBy = fieldName;
this.sortedDirection = sortDirection;
}Keep sortedBy set to the column's own fieldName so the arrow stays on the right header.
Sorting related fields
The datatable does not read dot paths such as Account.Name from fieldName. You flatten the row before passing it to the table, for example { ...contact, AccountName: contact.Account?.Name }. Use the flattened name, AccountName, in the column, in sortedBy, and in the sort function.
Sorting a frozen array
The error Cannot assign to read only property (or a silent failure) means you sorted the wired array directly. Always copy first.
Row order jumps while selecting
Row selection is tracked by key-field value, so reordering rows does not lose selections. If selections seem to vanish after a sort, check that key-field is unique and that rows still contain it after any transformation you apply.
Client-side sorting only covers loaded rows
The Apex method in this tutorial returns LIMIT 50. A client-side sort reorders those 50 rows. If the object has 5,000 contacts, a user who sorts by Name descending sees the last names within the first 50, not the last names in the whole table.
This is correct only when you load the entire dataset. When you load a page of a larger set, sort on the server. The component passes the sort field and direction to Apex, which applies ORDER BY.
public with sharing class ContactSortController {
private static final Set<String> SORTABLE_FIELDS =
new Set<String>{ 'Name', 'Email', 'Birthdate' };
@AuraEnabled(cacheable=true)
public static List<Contact> getContactsSorted(
String sortField,
String sortDirection
) {
String field = SORTABLE_FIELDS.contains(sortField) ? sortField : 'Name';
String direction = sortDirection == 'desc' ? 'DESC' : 'ASC';
String soql =
'SELECT Id, Name, Email, Phone, Birthdate FROM Contact ' +
'WITH USER_MODE ORDER BY ' + field + ' ' + direction +
' NULLS LAST LIMIT 50';
return Database.query(soql);
}
}The method never inserts sortField into the query unless it is in the allowed set. This blocks SOQL injection, because both values arrive from the browser and cannot be trusted.
On the component side, make the sort state reactive parameters of the wire. The handler then only stores the state, and the wire reruns when it changes:
import getContactsSorted from '@salesforce/apex/ContactSortController.getContactsSorted';
sortedBy = 'Name';
sortedDirection = 'asc';
@wire(getContactsSorted, {
sortField: '$sortedBy',
sortDirection: '$sortedDirection'
})
wiredContacts(result) {
this.wiredResult = result;
const { data, error } = result;
if (data) {
this.data = data;
this.error = undefined;
} else if (error) {
this.error = error;
this.data = [];
}
}
handleSort(event) {
this.sortedBy = event.detail.fieldName;
this.sortedDirection = event.detail.sortDirection;
}Initialize sortedBy to a real value. A wire with a reactive parameter that is undefined does not call Apex at all, so the table would stay empty.
Choosing between the two
| Criterion | Client-side | Server-side |
|---|---|---|
| Rows loaded | All rows that will ever be shown | A page or limited subset of a larger set |
| Response to a click | Immediate | One round trip, and cached results make repeats fast |
| Sort rules | Written in JavaScript, easy to customize | Limited to what SOQL `ORDER BY` supports |
| Security risk | None added | Field names must be whitelisted |
| Computed columns | Easy to sort | Cannot sort unless the value is a queryable field |
Summary of the sort contract
- Mark each sortable column with
sortable: true. - Handle
onsortand readfieldNameandsortDirectionfromevent.detail. - Sort a copy of the data, or ask the server for a sorted list.
- Store the state and pass it back through
sorted-byandsorted-direction. - Reapply the sort whenever the data is replaced or extended.
Exercise
A user clicks the Email header. The rows reorder correctly, but no sort arrow appears on any column, and after an inline edit saves and the data refreshes, the rows return to the server's order. What two changes fix both problems?
Show answer
First, bind sorted-by={sortedBy} and sorted-direction={sortedDirection} on the table and set them in handleSort from event.detail.fieldName and event.detail.sortDirection. The arrow needs both, and sortedBy must equal the column's fieldName. Second, in the wire handler, run sortRows(data, this.sortedBy, this.sortedDirection) on new data when sortedBy is set, so the sort survives a refresh. Without this step the table receives the server's order while the arrow still shows the old sort.
Exercise
Your table loads the first 50 of 4,000 accounts. Name the problem with client-side sorting here, and name the check you need in the Apex method that takes the sort field.
Show answer
A client-side sort only reorders the 50 loaded rows, so "Z to A" does not show the last accounts in the data. Sort on the server with ORDER BY and pass the field and direction as reactive wire parameters. In Apex, check the incoming field name against a fixed set of allowed field names and fall back to a default, because the value comes from the browser and would otherwise allow SOQL injection.