Skip to content

Commit

Permalink
fix(table): correctly sort columns with mixed data types
Browse files Browse the repository at this point in the history
  • Loading branch information
Hugoer committed Aug 21, 2020
1 parent d96de48 commit 21f2df3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/material/table/table-data-source.spec.ts
Expand Up @@ -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']);
});
});
});

Expand Down
11 changes: 11 additions & 0 deletions src/material/table/table-data-source.ts
Expand Up @@ -148,6 +148,17 @@ export class MatTableDataSource<T> extends DataSource<T> {
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.
Expand Down

0 comments on commit 21f2df3

Please sign in to comment.