Skip to content

Instantly share code, notes, and snippets.

@tkhduracell
Last active September 29, 2020 08:04
Show Gist options
  • Save tkhduracell/50587846f8774461d6bfdd3970339e50 to your computer and use it in GitHub Desktop.
Save tkhduracell/50587846f8774461d6bfdd3970339e50 to your computer and use it in GitHub Desktop.
Typescript: Filter array/list of objects based on attributes filter
/**
* Filters an array of objects (one level-depth) with multiple criteria.
*/
export function filterArray<T extends Record<string, string | number | undefined>>(array: T[], filters: Partial<T>): T[] {
const filterKeys = Object.entries(filters);
return array.filter(item => {
return filterKeys.every(([filterKey, filterValue]) => {
return filterKey in item && item[filterKey] === filterValue
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment