Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ZackDeRose/6be21bb977735a40df8616e299e8e7d7 to your computer and use it in GitHub Desktop.
Save ZackDeRose/6be21bb977735a40df8616e299e8e7d7 to your computer and use it in GitHub Desktop.
Searching then sorting for "Angular CDK Tables" article
combineLatest(this.heroes$, this.searchFormControl.valueChanges, this.sortKey$, this.sortDirection$)
.subscribe(([changedHeroData, searchTerm, sortKey, sortDirection]) => {
const heroesArray = Object.values(changedHeroData);
let filteredHeroes: any[];
if (!searchTerm) {
filteredHeroes = heroesArray;
} else {
const filteredResults = heroesArray.filter(hero => {
return Object.values(hero).reduce((prev, curr) => {
return prev || curr.toString().toLowerCase().includes(searchTerm.toLowerCase());
}, false);
});
filteredHeroes = filteredResults;
}
const sortedHeroes = filteredHeroes.sort((a, b) => {
if(a[sortKey] > b[sortKey]) return sortDirection === 'asc' ? 1 : -1;
if(a[sortKey] < b[sortKey]) return sortDirection === 'asc' ? -1 : 1;
return 0;
});
this.tableDataSource$.next(sortedHeroes);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment