Skip to content

Instantly share code, notes, and snippets.

@sidhantpanda
Created September 23, 2019 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sidhantpanda/4a159a85976ef639142027173ca82c27 to your computer and use it in GitHub Desktop.
Save sidhantpanda/4a159a85976ef639142027173ca82c27 to your computer and use it in GitHub Desktop.
Partition an array into 2 arrays in TypeScript
interface IPartitionFunction<T> {
(element: T): boolean;
}
/**
* Partitions an array in to two arrays based on `isValid` function
* @param array Array to partition
* @param isValid Function to test each item against
*/
const partition = <T>(array: T[], isValid: IPartitionFunction<T>): T[][] => {
return array.reduce(([pass, fail]: T[][], elem) => {
return isValid(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]];
}, [[], []]);
};
// Examples
const array = [1, 5, 32, 6, 2, 642, 62, 4];
const [pass, fail] = partition(array, item => item < 20);
console.log('pass', pass);
// pass [ 1, 5, 6, 2, 4 ]
console.log('fail', fail);
// fail [ 32, 642, 62 ]
const objectArray = [
{
key: 'key1',
value: 1
}, {
key: 'key2',
value: 5
}, {
key: 'key1',
value: 32
}, {
key: 'key1',
value: 78
}, {
key: 'key1',
value: 2
}, {
key: 'key1',
value: 642
}, {
key: 'key1',
value: 62
}, {
key: 'key1',
value: 4
}
];
const [passItems, failItems] = partition(objectArray, item => item.value < 15);
console.log('pass', passItems);
// pass [ { key: 'key1', value: 1 },
// { key: 'key2', value: 5 },
// { key: 'key5', value: 2 },
// { key: 'key8', value: 4 } ]
console.log('fail', failItems);
// fail [ { key: 'key3', value: 32 },
// { key: 'key4', value: 78 },
// { key: 'key6', value: 642 },
// { key: 'key7', value: 62 } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment