Skip to content

Commit 21f2df3

Browse files
authored
fix(table): correctly sort columns with mixed data types
(#20149)
1 parent d96de48 commit 21f2df3

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

src/material/table/table-data-source.spec.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,10 @@ describe('MatTableDataSource', () => {
4747
it('should be able to correctly sort an array of string', () => {
4848
testSortWithValues(['apples', 'bananas', 'cherries', 'lemons', 'strawberries']);
4949
});
50+
51+
it('should be able to correctly sort an array of strings and numbers', () => {
52+
testSortWithValues([3, 'apples', 'bananas', 'cherries', 'lemons', 'strawberries']);
53+
});
5054
});
5155
});
5256

src/material/table/table-data-source.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,17 @@ export class MatTableDataSource<T> extends DataSource<T> {
148148
let valueA = this.sortingDataAccessor(a, active);
149149
let valueB = this.sortingDataAccessor(b, active);
150150

151+
// If there are data in the column that can be converted to a number,
152+
// it must be ensured that the rest of the data
153+
// is of the same type so as not to order incorrectly.
154+
const valueAType = typeof valueA;
155+
const valueBType = typeof valueB;
156+
157+
if (valueAType !== valueBType) {
158+
if (valueAType === 'number') { valueA += ''; }
159+
if (valueBType === 'number') { valueB += ''; }
160+
}
161+
151162
// If both valueA and valueB exist (truthy), then compare the two. Otherwise, check if
152163
// one value exists while the other doesn't. In this case, existing value should come last.
153164
// This avoids inconsistent results when comparing values to undefined/null.

0 commit comments

Comments
 (0)