Array/Since
1.38.0partition
Splits an array into two arrays based on whether each element satisfies a predicate function.
partition(array, predicate):[T[], T[]]Parameters
arrayT[]requiredThe array whose elements should be divided into two groups.
predicate(item: T) => booleanrequiredA function that determines which group each element belongs to. Elements returning true are placed in the first array, while elements returning false are placed in the second array.
Returns
[T[], T[]]A tuple containing two arrays: the first contains elements for which the predicate returned true, and the second contains elements for which it returned false.
Examples
01
Basic usage
Separate numbers into even and odd groups.
TypeScript
import { partition } from "@cyref/js";
const numbers = [1, 2, 3, 4, 5, 6];
const [even, odd] = partition(
numbers,
(item) => item % 2 === 0,
);
console.log(even);
// [2, 4, 6]
console.log(odd);
// [1, 3, 5]02
Partition objects
Partition objects based on a property or condition.
TypeScript
import { partition } from "@cyref/js";
const users = [
{ name: "Amir", active: true },
{ name: "Sara", active: false },
{ name: "Reza", active: true },
];
const [activeUsers, inactiveUsers] = partition(
users,
(user) => user.active,
);
console.log(activeUsers);
// [
// { name: "Amir", active: true },
// { name: "Reza", active: true },
// ]
console.log(inactiveUsers);
// [
// { name: "Sara", active: false },
// ]03
Predicate returns false
Elements that do not satisfy the predicate are placed in the second array.
TypeScript
import { partition } from "@cyref/js";
const numbers = [1, 2, 3, 4];
const result = partition(
numbers,
(item) => item > 10,
);
console.log(result);
// [[], [1, 2, 3, 4]]04
Empty array
An empty array produces two empty arrays.
TypeScript
import { partition } from "@cyref/js";
const result = partition(
[],
(item) => item > 0,
);
console.log(result);
// [[], []]Built with@cyref/js·Official documentation