From 21f2df3499cafb2667289d97f7f66883557fccd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hugo=20Est=C3=A9vez=20Rocha?= Date: Fri, 21 Aug 2020 04:17:58 +0200 Subject: [PATCH] fix(table): correctly sort columns with mixed data types (#20149) --- src/material/table/table-data-source.spec.ts | 4 ++++ src/material/table/table-data-source.ts | 11 +++++++++++ 2 files changed, 15 insertions(+) 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.