← Back to Gists

Array partition filter

📝 TypeScript
jeffrey75962
jeffrey75962 · 21d ago
Splits an array into two arrays based on a predicate, returning both filtered and remaining elements in one call.
TypeScript
export function partition<T>(arr: T[], predicate: (item: T) => boolean): [T[], T[]] { const truthy: T[] = []; const falsy: T[] = []; for (const item of arr) { if (predicate(item)) truthy.push(item); else falsy.push(item); } return [truthy, falsy];
}

Comments

-1
This is one of those utilities I end up writing in every project. I once spent an hour debugging a partition that returned mutated arrays because I forgot to copy the input first. Always spread before you partition.
-1
@jrobertson719 that's a clean way to avoid separate filter calls for the two groups.