Last active
June 28, 2025 10:17
-
-
Save kirpalmakanga/9223d97d04f302b208b930ec8e3931e0 to your computer and use it in GitHub Desktop.
filter and map array in a single loop
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
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