partition

Partitions an array into two arrays based on a given callback ie predicate.

1.
/**
2.
* Partitions an array into two arrays based on a given callback ie predicate.
3.
**/
4.
const partition = <T,>(
5.
arr: T[],
6.
predicate: (value: T, i: number, arr: T[]) => boolean,
7.
): [T[], T[]] => {
8.
const pass: T[] = [];
9.
const fail: T[] = [];
10.
arr.forEach((...args) => {
11.
// run the predicate function on each element in the array
12.
// and push the element to the appropriate array
13.
(predicate(...args) ? pass : fail).push(args[0]);
14.
});
15.
return [pass, fail];
16.
};
17.
18.
export default partition;

1. Installtion

npx @jrtilak/lazykit add partition

2. Parameters

  • arr (T[])
    The array to be partitioned into two groups based on the provided predicate function.

  • predicate ((value: T, i: number, arr: T[]) => boolean)
    A callback function that is invoked for each element in the array. It receives the current element, its index, and the original array as arguments. The function should return true for elements that should be included in the first returned array and false for those that should be included in the second.

3. Returns

  • [T[], T[]]
    Returns a tuple containing two arrays:
    • The first array contains elements for which the predicate returned true.
    • The second array contains elements for which the predicate returned false.

4. Type Parameters

  • T
    The type of elements in the array. This allows the function to work with arrays of any type, ensuring type safety for the partitioned elements.

5. Usage

1. Partitioning even and odd numbers

1.
import partition from '@/helpers/partition';
2.
3.
const numbers = [1, 2, 3, 4, 5, 6];
4.
const [evens, odds] = partition(numbers, (num) => num % 2 === 0);
5.
6.
console.log(evens); // Output: [2, 4, 6]
7.
console.log(odds); // Output: [1, 3, 5]

2. Partitioning by object property

1.
import partition from '@/helpers/partition';
2.
3.
const people = [
4.
{ name: 'Alice', active: true },
5.
{ name: 'Bob', active: false },
6.
{ name: 'Charlie', active: true },
7.
];
8.
9.
const [active, inactive] = partition(people, (person) => person.active);
10.
11.
console.log(active); // Output: [{ name: 'Alice', active: true }, { name: 'Charlie', active: true }]
12.
console.log(inactive); // Output: [{ name: 'Bob', active: false }]

3. Partition strings by length

1.
import partition from '@/helpers/partition';
2.
3.
const words = ["short", "exceedingly long", "medium", "tiny"];
4.
const [longWords, shortWords] = partition(words, (word) => word.length > 5);
5.
6.
console.log(longWords); // Output: ["exceedingly long", "medium"]
7.
console.log(shortWords); // Output: ["short", "tiny"]