partition

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

1. Code

/**
 * Partitions an array into two separate arrays based on a given predicate.
 *
 * @template T - The type of elements in the array.
 * @param {T[]} arr - The array to be partitioned.
 * @param {(value: T, index: number, array: T[]) => boolean} predicate - The predicate function used to determine the partition.
 * @returns {[T[], T[]]} - An array containing two arrays: the first array contains elements that satisfy the predicate, and the second array contains elements that do not satisfy the predicate.
 */
const partition = <T>(
  arr: T[],
  predicate: (value: T, i: number, arr: T[]) => boolean
): [T[], T[]] => {
  const pass: T[] = [];
  const fail: T[] = [];
  arr.forEach((...args) => {
    // run the predicate function on each element in the array
    // and push the element to the appropriate array
    (predicate(...args) ? pass : fail).push(args[0]);
  });
  return [pass, fail];
};

export default partition;

2. Installation

npx @jrtilak/lazykit@latest add partition -ts

3. Description

The partition function takes an array and a predicate function as parameters and returns a tuple of two arrays. The first array contains all elements of the original array for which the predicate function returns true, and the second array contains all elements for which the predicate function returns false.

The predicate function is a callback function that you provide, which is called for each element in the array. It receives three arguments: the current element, its index, and the original array. The predicate function should return a boolean value.

The partition function creates two empty arrays, pass and fail, and then iterates over the original array using the forEach method. For each element, it calls the predicate function and pushes the element to the pass array if the predicate returns true, and to the fail array if the predicate returns false.

Finally, the partition function returns a tuple containing the pass and fail arrays. This function does not modify the original array.

4. Props

Prop

Type

Default Value

array*array---
predicate*function---

5. Examples

import partition from ".";

const arr = [1, 2, 3, 4, 5];
partition(arr, (value) => value % 2 === 0);
// Expected: [[2, 4], [1, 3, 5]]