Skip to content

Instantly share code, notes, and snippets.

@n18l
Last active December 8, 2021 23:27
Show Gist options
  • Save n18l/561144bd2c73cf949298425cd5d4830c to your computer and use it in GitHub Desktop.
Save n18l/561144bd2c73cf949298425cd5d4830c to your computer and use it in GitHub Desktop.
A function for partitioning an array based on the result of a filter function, rather than discarding the failed filter results. Sane people can also just run two `Array.filter()` methods.
/**
* Divides one array into two based on a filter function, returning the results
* of the filter as a [pass, fail] tuple.
*
* @param array The array to partition into separate arrays based on the provided filter.
* @param filterFunction The filter function to use to determine how each array item should be partitioned.
*
* @returns A tuple of partitioned array items, functionally equivalent to `[pass, fail]` in relation to the provided
* filter function.
*/
function partitionArray(array, filterFunction) {
return array.reduce(
(groups, item) => {
// Determine if this item should be placed in the pass (0) or fail (1)
// group based on the results of the filter function.
const groupIndex = filterFunction(item) ? 0 : 1;
// Place the item in the appropriate group.
groups[groupIndex].push(item);
return groups;
},
[[], []]
);
}
/**
* Divides one array into two based on a filter function, returning the results
* of the filter as a [pass, fail] tuple.
*
* @param array The array to partition into separate arrays based on the provided filter.
* @param filterFunction The filter function to use to determine how each array item should be partitioned.
*
* @returns A tuple of partitioned array items, functionally equivalent to `[pass, fail]` in relation to the provided
* filter function.
*/
function partitionArray<TItem>(
array: TItem[],
filterFunction: (item: TItem) => boolean
): [TItem[], TItem[]] {
return array.reduce(
(groups, item) => {
// Determine if this item should be placed in the pass (0) or fail (1)
// group based on the results of the filter function.
const groupIndex = filterFunction(item) ? 0 : 1;
// Place the item in the appropriate group.
groups[groupIndex].push(item);
return groups;
},
[[], []] as [TItem[], TItem[]]
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment