Skip to content

Instantly share code, notes, and snippets.

@kirpalmakanga
Last active June 28, 2025 10:17
Show Gist options
  • Save kirpalmakanga/9223d97d04f302b208b930ec8e3931e0 to your computer and use it in GitHub Desktop.
Save kirpalmakanga/9223d97d04f302b208b930ec8e3931e0 to your computer and use it in GitHub Desktop.
filter and map array in a single loop
function filterMap<T extends unknown, R extends unknown>(
arr: T[],
filterFn: (item: T, index: number) => boolean,
mapFn: (item: T, index: number) => R
) {
return arr.reduce((acc, item, i) => {
if (filterFn(item, i)) acc.push(mapFn(item, i));
return acc;
}, [] as R[]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment