Created
July 18, 2018 04:02
-
-
Save ZackDeRose/6be21bb977735a40df8616e299e8e7d7 to your computer and use it in GitHub Desktop.
Searching then sorting for "Angular CDK Tables" article
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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