Function partition

  • Returns a tuple of two arrays with the first one containing all elements in the given array that match the given predicate and the second one containing all that do not.

    Type Parameters

    • T

      The type of the elements in the array.

    Parameters

    • array: Iterable<T, any, any>

      The array to partition.

    • predicate: ((el: T) => boolean)

      The predicate function to determine which array an element belongs to.

        • (el): boolean
        • Parameters

          • el: T

          Returns boolean

    Returns [T[], T[]]

    A tuple of two arrays. The first array contains all elements that match the predicate, the second contains all elements that do not.

    import { partition } from "@std/collections/partition";
    import { assertEquals } from "@std/assert";

    const numbers = [5, 6, 7, 8, 9];
    const [even, odd] = partition(numbers, (it) => it % 2 === 0);

    assertEquals(even, [6, 8]);
    assertEquals(odd, [5, 7, 9]);
  • Returns a tuple of two arrays with the first one containing all elements in the given array that match the given predicate and the second one containing all that do not.

    This version of the function is a type-guard version of the function. It allows you to specify a type-guard predicate function that narrows the type of the elements in the array.

    Type Parameters

    • T

      The type of the elements in the array.

    • U

      The type of the elements that match the predicate.

    Parameters

    • array: Iterable<T, any, any>

      The array to partition.

    • predicate: ((el: T) => el is U)

      The type-guard predicate function to determine which array an element belongs to.

        • (el): el is U
        • Parameters

          • el: T

          Returns el is U

    Returns [U[], Exclude<T, U>[]]

    A tuple of two arrays. The first array contains all elements that match the predicate, the second contains all elements that do not.

    import { partition } from "@std/collections/partition";
    import { assertEquals } from "@std/assert";

    const numbers = [5, 6, 7, 8, 9];
    const [even, odd] = partition(numbers, (it) => it % 2 === 0);

    assertEquals(even, [6, 8]);
    assertEquals(odd, [5, 7, 9]);