Skip to content

Instantly share code, notes, and snippets.

@Aidurber
Last active June 19, 2019 09:06
Show Gist options
  • Save Aidurber/9d460ca0afafce8ecbb4b55d0c72fead to your computer and use it in GitHub Desktop.
Save Aidurber/9d460ca0afafce8ecbb4b55d0c72fead to your computer and use it in GitHub Desktop.
Type safe text search of collection
/**
* Perform text search on collection of object for multiple keys
*
* @export
* @template T
* @param {T[]} values - The collection
* @param {Array<keyof T>} keys - An array of properties on the object (array of strings)
* @param {string} term - Search term
* @returns
*/
export function filterByTerm<T>(
values: T[],
keys: Array<keyof T>,
term: string
) {
const loweredTerm = term.toLocaleLowerCase();
return (values || []).filter(value =>
keys.some(
key =>
value[key] &&
value[key]
.toString()
.toLocaleLowerCase()
.includes(loweredTerm)
)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment