0
# Built-in Functions
1
2
Pre-built sorting, filtering, and aggregation functions for common table operations. These functions provide robust, tested implementations for standard data operations.
3
4
## Capabilities
5
6
### Sorting Functions
7
8
Built-in sorting functions for different data types and sorting requirements.
9
10
```typescript { .api }
11
/** Built-in sorting functions collection */
12
const sortingFns: {
13
alphanumeric: SortingFn<any>;
14
alphanumericCaseSensitive: SortingFn<any>;
15
text: SortingFn<any>;
16
textCaseSensitive: SortingFn<any>;
17
datetime: SortingFn<any>;
18
basic: SortingFn<any>;
19
};
20
21
/** Built-in sorting function names */
22
type BuiltInSortingFn = keyof typeof sortingFns;
23
24
/** Regular expression for splitting alphanumeric strings */
25
const reSplitAlphaNumeric: RegExp;
26
```
27
28
**Usage Examples:**
29
30
```typescript
31
import { sortingFns } from "@tanstack/table-core";
32
33
// Using built-in sorting functions in column definitions
34
const columns = [
35
columnHelper.accessor('name', {
36
header: 'Name',
37
sortingFn: 'alphanumeric', // Mixed letters and numbers
38
}),
39
columnHelper.accessor('code', {
40
header: 'Code',
41
sortingFn: 'alphanumericCaseSensitive', // Case-sensitive mixed sorting
42
}),
43
columnHelper.accessor('description', {
44
header: 'Description',
45
sortingFn: 'text', // Fast text sorting
46
}),
47
columnHelper.accessor('label', {
48
header: 'Label',
49
sortingFn: 'textCaseSensitive', // Case-sensitive text sorting
50
}),
51
columnHelper.accessor('createdAt', {
52
header: 'Created',
53
sortingFn: 'datetime', // Date/time sorting
54
}),
55
columnHelper.accessor('score', {
56
header: 'Score',
57
sortingFn: 'basic', // Basic value comparison
58
}),
59
];
60
61
// Access sorting functions directly
62
const result = sortingFns.alphanumeric(rowA, rowB, 'columnId');
63
```
64
65
### Individual Sorting Functions
66
67
Detailed documentation for each built-in sorting function.
68
69
```typescript { .api }
70
/**
71
* Alphanumeric sorting with mixed text and numbers
72
* Handles numeric sequences within strings properly
73
* Case-insensitive comparison
74
*/
75
function alphanumeric<TData extends RowData>(
76
rowA: Row<TData>,
77
rowB: Row<TData>,
78
columnId: string
79
): number;
80
81
/**
82
* Case-sensitive alphanumeric sorting
83
* Same as alphanumeric but preserves case
84
*/
85
function alphanumericCaseSensitive<TData extends RowData>(
86
rowA: Row<TData>,
87
rowB: Row<TData>,
88
columnId: string
89
): number;
90
91
/**
92
* Fast text sorting for string values
93
* Case-insensitive, optimized for speed
94
* Less numeric support than alphanumeric
95
*/
96
function text<TData extends RowData>(
97
rowA: Row<TData>,
98
rowB: Row<TData>,
99
columnId: string
100
): number;
101
102
/**
103
* Case-sensitive text sorting
104
* Same as text but preserves case
105
*/
106
function textCaseSensitive<TData extends RowData>(
107
rowA: Row<TData>,
108
rowB: Row<TData>,
109
columnId: string
110
): number;
111
112
/**
113
* Date and time sorting
114
* Handles Date objects and nullish values
115
* Uses comparison operators for performance
116
*/
117
function datetime<TData extends RowData>(
118
rowA: Row<TData>,
119
rowB: Row<TData>,
120
columnId: string
121
): number;
122
123
/**
124
* Basic value comparison sorting
125
* Simple comparison using > and < operators
126
* Works with numbers, strings, and other comparable types
127
*/
128
function basic<TData extends RowData>(
129
rowA: Row<TData>,
130
rowB: Row<TData>,
131
columnId: string
132
): number;
133
```
134
135
**Usage Examples:**
136
137
```typescript
138
// Example data types that work well with each sorting function
139
140
// alphanumeric: "item1", "item2", "item10", "item20"
141
// Correctly sorts as: item1, item2, item10, item20 (not item1, item10, item2, item20)
142
143
// alphanumericCaseSensitive: "Item1", "item2", "Item10"
144
// Sorts with case sensitivity preserved
145
146
// text: Fast sorting for plain text fields
147
// Best for: names, descriptions, labels
148
149
// textCaseSensitive: "Apple", "banana", "Zebra"
150
// Maintains case-sensitive ordering
151
152
// datetime: Date objects, null, undefined
153
const dateColumn = columnHelper.accessor('createdAt', {
154
sortingFn: 'datetime',
155
cell: info => info.getValue()?.toLocaleDateString(),
156
});
157
158
// basic: numbers, booleans, simple comparisons
159
const numericColumn = columnHelper.accessor('count', {
160
sortingFn: 'basic', // Simple numeric comparison
161
});
162
```
163
164
### Filter Functions
165
166
Built-in filter functions for various filtering patterns and data types.
167
168
```typescript { .api }
169
/** Built-in filter functions collection */
170
const filterFns: {
171
includesString: FilterFn<any>;
172
includesStringSensitive: FilterFn<any>;
173
equalsString: FilterFn<any>;
174
arrIncludes: FilterFn<any>;
175
arrIncludesAll: FilterFn<any>;
176
arrIncludesSome: FilterFn<any>;
177
equals: FilterFn<any>;
178
weakEquals: FilterFn<any>;
179
inNumberRange: FilterFn<any>;
180
};
181
182
/** Built-in filter function names */
183
type BuiltInFilterFn = keyof typeof filterFns;
184
```
185
186
**Usage Examples:**
187
188
```typescript
189
import { filterFns } from "@tanstack/table-core";
190
191
// Using built-in filter functions in column definitions
192
const columns = [
193
columnHelper.accessor('name', {
194
header: 'Name',
195
filterFn: 'includesString', // Case-insensitive partial match
196
}),
197
columnHelper.accessor('code', {
198
header: 'Code',
199
filterFn: 'includesStringSensitive', // Case-sensitive partial match
200
}),
201
columnHelper.accessor('status', {
202
header: 'Status',
203
filterFn: 'equalsString', // Exact string match
204
}),
205
columnHelper.accessor('tags', {
206
header: 'Tags',
207
filterFn: 'arrIncludes', // Array contains value
208
}),
209
columnHelper.accessor('id', {
210
header: 'ID',
211
filterFn: 'equals', // Strict equality
212
}),
213
columnHelper.accessor('age', {
214
header: 'Age',
215
filterFn: 'inNumberRange', // Numeric range filter
216
}),
217
];
218
```
219
220
### Individual Filter Functions
221
222
Detailed documentation for each built-in filter function.
223
224
```typescript { .api }
225
/**
226
* Case-insensitive string inclusion filter
227
* Checks if cell value contains the filter value
228
* Converts both to lowercase for comparison
229
*/
230
function includesString(
231
row: Row<any>,
232
columnId: string,
233
filterValue: string
234
): boolean;
235
236
/**
237
* Case-sensitive string inclusion filter
238
* Checks if cell value contains the filter value
239
* Preserves original case for comparison
240
*/
241
function includesStringSensitive(
242
row: Row<any>,
243
columnId: string,
244
filterValue: string
245
): boolean;
246
247
/**
248
* Case-insensitive string equality filter
249
* Checks if cell value exactly equals filter value
250
* Converts both to lowercase for comparison
251
*/
252
function equalsString(
253
row: Row<any>,
254
columnId: string,
255
filterValue: string
256
): boolean;
257
258
/**
259
* Array inclusion filter
260
* Checks if cell array contains the filter value
261
* Uses array.includes() method
262
*/
263
function arrIncludes(
264
row: Row<any>,
265
columnId: string,
266
filterValue: unknown
267
): boolean;
268
269
/**
270
* Array includes all filter
271
* Checks if cell array contains all values in filter array
272
* All filter values must be present in cell array
273
*/
274
function arrIncludesAll(
275
row: Row<any>,
276
columnId: string,
277
filterValue: unknown[]
278
): boolean;
279
280
/**
281
* Array includes some filter
282
* Checks if cell array contains any values in filter array
283
* At least one filter value must be present in cell array
284
*/
285
function arrIncludesSome(
286
row: Row<any>,
287
columnId: string,
288
filterValue: unknown[]
289
): boolean;
290
291
/**
292
* Strict equality filter
293
* Uses === comparison between cell value and filter value
294
* No type coercion performed
295
*/
296
function equals(
297
row: Row<any>,
298
columnId: string,
299
filterValue: unknown
300
): boolean;
301
302
/**
303
* Weak equality filter
304
* Uses == comparison between cell value and filter value
305
* Allows type coercion (e.g., "1" == 1)
306
*/
307
function weakEquals(
308
row: Row<any>,
309
columnId: string,
310
filterValue: unknown
311
): boolean;
312
313
/**
314
* Number range filter
315
* Checks if numeric cell value falls within min/max range
316
* Handles null values and invalid numbers gracefully
317
*/
318
function inNumberRange(
319
row: Row<any>,
320
columnId: string,
321
filterValue: [number, number]
322
): boolean;
323
```
324
325
### Filter Function Properties
326
327
Built-in filter functions include additional properties for enhanced functionality.
328
329
```typescript { .api }
330
/** Auto-removal function for includesString */
331
includesString.autoRemove = (val: any) => testFalsey(val);
332
333
/** Auto-removal function for equalsString */
334
equalsString.autoRemove = (val: any) => testFalsey(val);
335
336
/** Auto-removal function for equals */
337
equals.autoRemove = (val: any) => testFalsey(val);
338
339
/** Filter value resolver for inNumberRange */
340
inNumberRange.resolveFilterValue = (val: [any, any]) => [number, number];
341
342
/** Auto-removal function for inNumberRange */
343
inNumberRange.autoRemove = (val: any) =>
344
testFalsey(val) || (testFalsey(val[0]) && testFalsey(val[1]));
345
```
346
347
**Usage Examples:**
348
349
```typescript
350
// String filtering examples
351
const nameFilter = filterFns.includesString;
352
const isMatch = nameFilter(row, 'name', 'john'); // Matches "John", "johnny", etc.
353
354
// Array filtering examples
355
const tagsData = { tags: ['react', 'typescript', 'table'] };
356
const hasReact = filterFns.arrIncludes(row, 'tags', 'react'); // true
357
const hasAll = filterFns.arrIncludesAll(row, 'tags', ['react', 'vue']); // false
358
const hasSome = filterFns.arrIncludesSome(row, 'tags', ['react', 'vue']); // true
359
360
// Range filtering examples
361
const ageData = { age: 25 };
362
const inRange = filterFns.inNumberRange(row, 'age', [18, 65]); // true
363
364
// Equality filtering examples
365
const statusData = { status: 'active', count: 5 };
366
const exactMatch = filterFns.equals(row, 'status', 'active'); // true
367
const numericMatch = filterFns.weakEquals(row, 'count', '5'); // true (string coerced to number)
368
```
369
370
### Aggregation Functions
371
372
Built-in aggregation functions for grouped data calculations.
373
374
```typescript { .api }
375
/** Built-in aggregation functions collection */
376
const aggregationFns: {
377
sum: AggregationFn<any>;
378
min: AggregationFn<any>;
379
max: AggregationFn<any>;
380
extent: AggregationFn<any>;
381
mean: AggregationFn<any>;
382
median: AggregationFn<any>;
383
unique: AggregationFn<any>;
384
uniqueCount: AggregationFn<any>;
385
count: AggregationFn<any>;
386
};
387
388
/** Built-in aggregation function names */
389
type BuiltInAggregationFn = keyof typeof aggregationFns;
390
```
391
392
**Usage Examples:**
393
394
```typescript
395
import { aggregationFns } from "@tanstack/table-core";
396
397
// Using aggregation functions in column definitions
398
const columns = [
399
columnHelper.accessor('department', {
400
header: 'Department',
401
enableGrouping: true,
402
}),
403
columnHelper.accessor('salary', {
404
header: 'Salary',
405
aggregationFn: 'sum', // Sum all salaries in group
406
aggregatedCell: ({ getValue }) =>
407
`$${getValue().toLocaleString()}`,
408
}),
409
columnHelper.accessor('experience', {
410
header: 'Experience',
411
aggregationFn: 'mean', // Average experience in group
412
aggregatedCell: ({ getValue }) =>
413
`${Math.round(getValue())} years`,
414
}),
415
columnHelper.accessor('score', {
416
header: 'Score',
417
aggregationFn: 'extent', // Min and max scores
418
aggregatedCell: ({ getValue }) => {
419
const [min, max] = getValue();
420
return `${min} - ${max}`;
421
},
422
}),
423
];
424
```
425
426
### Individual Aggregation Functions
427
428
Detailed documentation for each built-in aggregation function.
429
430
```typescript { .api }
431
/**
432
* Sum aggregation - adds numeric values
433
* Treats non-numeric values as 0
434
* Works with child row aggregated values
435
*/
436
function sum(
437
columnId: string,
438
leafRows: Row<any>[],
439
childRows: Row<any>[]
440
): number;
441
442
/**
443
* Minimum aggregation - finds smallest numeric value
444
* Ignores null/undefined values
445
* Handles NaN values gracefully
446
*/
447
function min(
448
columnId: string,
449
leafRows: Row<any>[],
450
childRows: Row<any>[]
451
): number | undefined;
452
453
/**
454
* Maximum aggregation - finds largest numeric value
455
* Ignores null/undefined values
456
* Handles NaN values gracefully
457
*/
458
function max(
459
columnId: string,
460
leafRows: Row<any>[],
461
childRows: Row<any>[]
462
): number | undefined;
463
464
/**
465
* Extent aggregation - returns [min, max] array
466
* Combines min and max calculations
467
* Returns undefined if no valid values
468
*/
469
function extent(
470
columnId: string,
471
leafRows: Row<any>[],
472
childRows: Row<any>[]
473
): [number, number] | undefined;
474
475
/**
476
* Mean aggregation - calculates average of numeric values
477
* Excludes null/undefined/NaN values from calculation
478
* Returns undefined if no valid values
479
*/
480
function mean(
481
columnId: string,
482
leafRows: Row<any>[],
483
childRows: Row<any>[]
484
): number | undefined;
485
486
/**
487
* Median aggregation - finds middle value when sorted
488
* Handles even/odd number of values appropriately
489
* Only works with numeric arrays
490
*/
491
function median(
492
columnId: string,
493
leafRows: Row<any>[],
494
childRows: Row<any>[]
495
): number | undefined;
496
497
/**
498
* Unique aggregation - returns array of unique values
499
* Uses Set for deduplication
500
* Preserves all data types
501
*/
502
function unique(
503
columnId: string,
504
leafRows: Row<any>[],
505
childRows: Row<any>[]
506
): any[];
507
508
/**
509
* Unique count aggregation - counts distinct values
510
* Uses Set size for counting
511
* More memory efficient than unique for just counts
512
*/
513
function uniqueCount(
514
columnId: string,
515
leafRows: Row<any>[],
516
childRows: Row<any>[]
517
): number;
518
519
/**
520
* Count aggregation - counts total rows
521
* Simply returns array length
522
* Useful for "Total Items" type aggregations
523
*/
524
function count(
525
columnId: string,
526
leafRows: Row<any>[],
527
childRows: Row<any>[]
528
): number;
529
```
530
531
**Usage Examples:**
532
533
```typescript
534
// Aggregation function examples with different data types
535
536
// Numeric aggregations
537
const salesData = [
538
{ region: 'North', sales: 1000 },
539
{ region: 'North', sales: 1500 },
540
{ region: 'South', sales: 800 },
541
];
542
543
// sum: North = 2500, South = 800
544
// mean: North = 1250, South = 800
545
// min: North = 1000, South = 800
546
// max: North = 1500, South = 800
547
// extent: North = [1000, 1500], South = [800, 800]
548
549
// Count aggregations
550
// count: North = 2, South = 1
551
552
// Text aggregations
553
const employeeData = [
554
{ dept: 'Engineering', skill: 'JavaScript' },
555
{ dept: 'Engineering', skill: 'TypeScript' },
556
{ dept: 'Engineering', skill: 'JavaScript' }, // duplicate
557
];
558
559
// unique: Engineering = ['JavaScript', 'TypeScript']
560
// uniqueCount: Engineering = 2
561
562
// Using aggregations with grouping
563
const table = createTable({
564
data: salesData,
565
columns: [
566
columnHelper.accessor('region', {
567
enableGrouping: true,
568
}),
569
columnHelper.accessor('sales', {
570
aggregationFn: 'sum',
571
aggregatedCell: ({ getValue }) => `$${getValue().toLocaleString()}`,
572
}),
573
],
574
getCoreRowModel: getCoreRowModel(),
575
getGroupedRowModel: getGroupedRowModel(),
576
state: {
577
grouping: ['region'],
578
},
579
});
580
```
581
582
### Function Type Definitions
583
584
Type definitions for creating custom functions that match the built-in patterns.
585
586
```typescript { .api }
587
/** Sorting function interface */
588
interface SortingFn<TData extends RowData> {
589
(rowA: Row<TData>, rowB: Row<TData>, columnId: string): number;
590
}
591
592
/** Filter function interface */
593
interface FilterFn<TData extends RowData> {
594
(
595
row: Row<TData>,
596
columnId: string,
597
filterValue: any,
598
addMeta?: (meta: FilterMeta) => void
599
): boolean;
600
autoRemove?: (filterValue: any, column?: Column<TData, unknown>) => boolean;
601
resolveFilterValue?: (filterValue: any) => any;
602
}
603
604
/** Aggregation function interface */
605
interface AggregationFn<TData extends RowData> {
606
(
607
columnId: string,
608
leafRows: Row<TData>[],
609
childRows: Row<TData>[]
610
): any;
611
}
612
```
613
614
These built-in functions provide robust, tested implementations that handle edge cases like null values, type coercion, and performance optimization. They serve as both ready-to-use solutions and examples for creating custom functions.