partition

collection

Creates an array of elements split into two groups, the first of which contains elements predicate returns truthy for, the second of which contains elements predicate returns falsy for.

Signature

partition<T>(collection: T[], predicate: (value: T) => boolean): [T[], T[]]

Parameters

NameTypeDescription
collectionT[]The collection to iterate over
predicate(value: T) => booleanThe function invoked per iteration

Returns

[T[], T[]] - Returns the array of grouped elements

Examples

Partition by active status

import { partition } from 'dashlite'

const users = [
  { name: 'barney', active: false },
  { name: 'fred', active: true },
  { name: 'pebbles', active: false }
]
const [active, inactive] = partition(users, (o) => o.active)
console.log(active.length, inactive.length)

Output:

1 2

Partition numbers

import { partition } from 'dashlite'

const [even, odd] = partition([1, 2, 3, 4], (n) => n % 2 === 0)
console.log(even)
console.log(odd)

Output:

[2, 4] [1, 3]

Available since version 1.2.0