Skip to content

fix(table-data-source): sort for mixed arrays #19109

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions src/material/table/table-data-source.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,16 @@ describe('MatTableDataSource', () => {
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']);
it('should be able to correctly sort array with mix of strings and numbers', () => {
testSortWithValues([-2, -1, 0, 1, 2, 'apples', 'avocados', 'bananas']);
});

it('should be able to correctly sort array with mix of strings, numbers, and undefined', () => {
testSortWithValues([undefined, -2, -1, 0, 1, 2, 'apples', 'avocados', 'bananas']);
});

it('should be able to correctly sort array with mix of strings, numbers, and null', () => {
testSortWithValues([null, -2, -1, 0, 1, 2, 'apples', 'avocados', 'bananas']);
});
});
});
Expand Down
22 changes: 17 additions & 5 deletions src/material/table/table-data-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,11 +165,23 @@ export class MatTableDataSource<T> extends DataSource<T> {
// If neither value exists, return 0 (equal).
let comparatorResult = 0;
if (valueA != null && valueB != null) {
// Check if one value is greater than the other; if equal, comparatorResult should remain 0.
if (valueA > valueB) {
comparatorResult = 1;
} else if (valueA < valueB) {
comparatorResult = -1;

// Check that both values have same type
if (typeof valueA === typeof valueB) {
// Check if one value is greater than the other;
// If equal, comparatorResult should remain 0.
if (valueA > valueB) {
comparatorResult = 1;
} else if (valueA < valueB) {
comparatorResult = -1;
}
} else {
// If one value is string and other is number than number must go first
if (typeof valueA === 'number' && typeof valueB === 'string') {
comparatorResult = -1;
} else if (typeof valueA === 'string' && typeof valueB === 'number') {
comparatorResult = 1;
}
}
} else if (valueA != null) {
comparatorResult = 1;
Expand Down