Skip to content

Instantly share code, notes, and snippets.

@pjflanagan
Created November 14, 2023 16:31
Show Gist options
  • Save pjflanagan/05a96856b911da57f35fa745c3fbd4eb to your computer and use it in GitHub Desktop.
Save pjflanagan/05a96856b911da57f35fa745c3fbd4eb to your computer and use it in GitHub Desktop.
A util function like filter that also returns an array that doesn't match
type Split<T> = [T[], T[]];
export function split<T>(arr: T[], isMatch: (item: T) => boolean): Split<T> {
return arr.reduce<Split<T>>((rv: [T[], T[]], item: T) => {
if (isMatch(item)) {
rv[0] = [...rv[0], item];
} else {
rv[1] = [...rv[1], item];
}
return rv;
}, [[], []] as Split<T>);
}
const [match, noMatch] = split([1,2,3,4,5], (i) => i % 2 === 0);
// match = [2, 4]
// noMatch = [1, 3, 5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment