Skip to content

partition

Splits an array into two groups based on a predicate function. The first group contains elements for which the predicate returns true, the second group contains the rest. null and undefined are treated as empty arrays and return [[], []].

Available since v2.0.0

import { partition } from '@helpers4/array';
partition<T>(array: readonly T[] | null | undefined, predicate: function): [T[], T[]]
ParameterTypeDescription
arrayreadonly T[] | null | undefinedThe array to partition
predicatefunctionFunction that returns true for elements in the first group

[T[], T[]] — A tuple of two arrays: [matching, non-matching]

Splits an array into even and odd numbers using a predicate.

partition([1, 2, 3, 4, 5], n => n % 2 === 0)
// => [[2, 4], [1, 3, 5]]

Partitions an array of objects based on a boolean property.

const users = [
  { name: 'Alice', active: true },
  { name: 'Bob', active: false },
  { name: 'Charlie', active: true },
];
partition(users, u => u.active)
// => [[Alice, Charlie], [Bob]]

Returns two empty arrays when the input is empty.

partition([], () => true)
// => [[], []]

View source on GitHub