diff --git a/src/material/table/table-data-source.spec.ts b/src/material/table/table-data-source.spec.ts index 98a1de02315b..0304e72594c0 100644 --- a/src/material/table/table-data-source.spec.ts +++ b/src/material/table/table-data-source.spec.ts @@ -47,6 +47,10 @@ describe('MatTableDataSource', () => { it('should be able to correctly sort an array of string', () => { testSortWithValues(['apples', 'bananas', 'cherries', 'lemons', 'strawberries']); }); + + it('should be able to correctly sort an array of strings and numbers', () => { + testSortWithValues([3, 'apples', 'bananas', 'cherries', 'lemons', 'strawberries']); + }); }); }); diff --git a/src/material/table/table-data-source.ts b/src/material/table/table-data-source.ts index a6e80a39b09c..8d3d834d44fd 100644 --- a/src/material/table/table-data-source.ts +++ b/src/material/table/table-data-source.ts @@ -148,6 +148,17 @@ export class MatTableDataSource extends DataSource { let valueA = this.sortingDataAccessor(a, active); let valueB = this.sortingDataAccessor(b, active); + // If there are data in the column that can be converted to a number, + // it must be ensured that the rest of the data + // is of the same type so as not to order incorrectly. + const valueAType = typeof valueA; + const valueBType = typeof valueB; + + if (valueAType !== valueBType) { + if (valueAType === 'number') { valueA += ''; } + if (valueBType === 'number') { valueB += ''; } + } + // If both valueA and valueB exist (truthy), then compare the two. Otherwise, check if // one value exists while the other doesn't. In this case, existing value should come last. // This avoids inconsistent results when comparing values to undefined/null.