What were all sort primed in the lightning-datatable sort example?

210    Asked by Aalapprabhakaran in Salesforce , Asked on Jun 1, 2023

 The example "Datatable with Sortable Column" (from the lightning-datatable documentation) includes this code where a primer parameter is declared and used in the sortBy function:


sortBy(field, reverse, primer) { const key = primer ? function (x) { return primer(x[field]); } : function (x) { return x[field]; }; return function (a, b) { a = key(a); b = key(b); return reverse * ((a > b) - (b > a)); }; } onHandleSort(event) { const { fieldName: sortedBy, sortDirection } = event.detail; const cloneData = [...this.data]; cloneData.sort(this.sortBy(sortedBy, sortDirection === 'asc' ? 1 : -1)); this.data = cloneData; this.sortDirection = sortDirection; this.sortedBy = sortedBy; }

In a quick test, it is always undefined. What is its purpose, when is it populated and where is it documented?


Answered by Clare Matthews

The answer to your question - What were all sort primed in the lightning-datatable sort example is -

primer is just a function that does something to "prime" the data. For example, you might use it to make all the values lowercase, or uppercase, or round to the second significant digit, or whatever else you might want to do.

Examples:

// sort by uppercase letters, works for anything that can be coerced to a string const uppercase = (x) => (x+'').toUpperCase(); this.sortBy(this.sortField, this.sortOrder, uppercase); // Sort non-empty values const truthy = (x) => (!!x); this.sortBy(this.sortField, this.sortOrder, truthy); // sort numbers in lexicographical order const toString = (x) => x+''; this.sortBy(this.sortField, this.sortOrder, toString);

It's useful to have this capability in many different sort algorithms, but the documentation doesn't actively use it, as you've observed.


Your Answer

Interviews

Parent Categories