I have a Javascript array that I would like to split into two based on whether a function called on each element returns true
or false
. Essentially
I ended up doing this because it's easy to understand (and fully typed with typescript).
const partition = (array: T[], isValid: (element: T) => boolean): [T[], T[]] => {
const pass: T[] = []
const fail: T[] = []
array.forEach(element => {
if (isValid(element)) {
pass.push(element)
} else {
fail.push(element)
}
})
return [pass, fail]
}
// usage
const [pass, fail] = partition([1, 2, 3, 4, 5], (element: number) => element > 3)