Skip to main content Link Search Menu Expand Document (external link)

Array overview

This module provides utility functions for working with arrays in TypeScript.

Added in v2.0.0


Table of contents


concatenating

append

Append an element to the end of an Iterable, creating a new NonEmptyArray.

Signature

export declare const append: {
  <B>(last: B): <A>(self: Iterable<A>) => [B | A, ...(B | A)[]]
  <A, B>(self: Iterable<A>, last: B): [A | B, ...(A | B)[]]
}

Example

import { Array } from "effect"

const original = [1, 2, 3]
const result = Array.append(original, 4)
assert.deepStrictEqual(result, [1, 2, 3, 4])

Added in v2.0.0

appendAll

Concatenates two arrays (or iterables), combining their elements. If either array is non-empty, the result is also a non-empty array.

Signature

export declare const appendAll: {
  <S extends Iterable<any>, T extends Iterable<any>>(
    that: T
  ): (self: S) => ReadonlyArray.OrNonEmpty<S, T, ReadonlyArray.Infer<S> | ReadonlyArray.Infer<T>>
  <A, B>(self: Iterable<A>, that: readonly [B, ...B[]]): [A | B, ...(A | B)[]]
  <A, B>(self: readonly [A, ...A[]], that: Iterable<B>): [A | B, ...(A | B)[]]
  <A, B>(self: Iterable<A>, that: Iterable<B>): (A | B)[]
}

Added in v2.0.0

prepend

Prepend an element to the front of an Iterable, creating a new NonEmptyArray.

Signature

export declare const prepend: {
  <B>(head: B): <A>(self: Iterable<A>) => [B | A, ...(B | A)[]]
  <A, B>(self: Iterable<A>, head: B): [A | B, ...(A | B)[]]
}

Example

import { Array } from "effect"

const original = [2, 3, 4]
const result = Array.prepend(original, 1)
assert.deepStrictEqual(result, [1, 2, 3, 4])

Added in v2.0.0

prependAll

Prepends the specified prefix array (or iterable) to the beginning of the specified array (or iterable). If either array is non-empty, the result is also a non-empty array.

Signature

export declare const prependAll: {
  <S extends Iterable<any>, T extends Iterable<any>>(
    that: T
  ): (self: S) => ReadonlyArray.OrNonEmpty<S, T, ReadonlyArray.Infer<S> | ReadonlyArray.Infer<T>>
  <A, B>(self: Iterable<A>, that: readonly [B, ...B[]]): [A | B, ...(A | B)[]]
  <A, B>(self: readonly [A, ...A[]], that: Iterable<B>): [A | B, ...(A | B)[]]
  <A, B>(self: Iterable<A>, that: Iterable<B>): (A | B)[]
}

Example

import { Array } from "effect"

const prefix = [0, 1]
const array = [2, 3]
const result = Array.prependAll(array, prefix)
assert.deepStrictEqual(result, [0, 1, 2, 3])

Added in v2.0.0

constructors

allocate

Creates a new Array of the specified length.

Signature

export declare const allocate: <A = never>(n: number) => (A | undefined)[]

Example

import { Array } from "effect"

const result = Array.allocate<number>(3)
assert.deepStrictEqual(result.length, 3)

Added in v2.0.0

empty

Signature

export declare const empty: <A = never>() => A[]

Added in v2.0.0

ensure

Creates a new Array from a value that might not be an iterable.

Signature

export declare const ensure: <A>(self: A | readonly A[]) => A[]

Example

import { Array } from "effect"

assert.deepStrictEqual(Array.ensure("a"), ["a"])
assert.deepStrictEqual(Array.ensure(["a"]), ["a"])
assert.deepStrictEqual(Array.ensure(["a", "b", "c"]), ["a", "b", "c"])

Added in v3.3.0

fromIterable

Creates a new Array from an iterable collection of values. If the input is already an array, it returns the input as-is. Otherwise, it converts the iterable collection to an array.

Signature

export declare const fromIterable: <A>(collection: Iterable<A>) => A[]

Example

import { Array } from "effect"

const set = new Set([1, 2, 3])
const result = Array.fromIterable(set)
assert.deepStrictEqual(result, [1, 2, 3])

Added in v2.0.0

make

Builds a NonEmptyArray from an non-empty collection of elements.

Signature

export declare const make: <Elements extends [any, ...any[]]>(
  ...elements: Elements
) => [Elements[number], ...Elements[number][]]

Example

import { Array } from "effect"

const result = Array.make(1, 2, 3)
assert.deepStrictEqual(result, [1, 2, 3])

Added in v2.0.0

makeBy

Return a NonEmptyArray of length n with element i initialized with f(i).

Note. n is normalized to an integer >= 1.

Signature

export declare const makeBy: <A>(n: number, f: (i: number) => A) => [A, ...A[]]

Example

import { makeBy } from "effect/Array"

assert.deepStrictEqual(
  makeBy(5, (n) => n * 2),
  [0, 2, 4, 6, 8]
)

Added in v2.0.0

of

Constructs a new NonEmptyArray<A> from the specified value.

Signature

export declare const of: <A>(a: A) => [A, ...A[]]

Added in v2.0.0

range

Return a NonEmptyArray containing a range of integers, including both endpoints.

Signature

export declare const range: (start: number, end: number) => [number, ...number[]]

Example

import { range } from "effect/Array"

assert.deepStrictEqual(range(1, 3), [1, 2, 3])

Added in v2.0.0

replicate

Return a NonEmptyArray containing a value repeated the specified number of times.

Note. n is normalized to an integer >= 1.

Signature

export declare const replicate: { (n: number): <A>(a: A) => [A, ...A[]]; <A>(a: A, n: number): [A, ...A[]] }

Example

import { Array } from "effect"

assert.deepStrictEqual(Array.replicate("a", 3), ["a", "a", "a"])

Added in v2.0.0

unfold

Signature

export declare const unfold: <B, A>(b: B, f: (b: B) => Option<readonly [A, B]>) => A[]

Added in v2.0.0

conversions

fromNullable

Signature

export declare const fromNullable: <A>(a: A) => NonNullable<A>[]

Added in v2.0.0

fromOption

Converts an Option to an array.

Signature

export declare const fromOption: <A>(self: Option<A>) => A[]

Example

import { Array, Option } from "effect"

assert.deepStrictEqual(Array.fromOption(Option.some(1)), [1])
assert.deepStrictEqual(Array.fromOption(Option.none()), [])

Added in v2.0.0

fromRecord

Takes a record and returns an array of tuples containing its keys and values.

Signature

export declare const fromRecord: <K extends string, A>(self: Readonly<Record<K, A>>) => [K, A][]

Example

import { Array } from "effect"

const x = { a: 1, b: 2, c: 3 }
assert.deepStrictEqual(Array.fromRecord(x), [
  ["a", 1],
  ["b", 2],
  ["c", 3]
])

Added in v2.0.0

do notation

Do

The “do simulation” for array allows you to sequentially apply operations to the elements of arrays, just as nested loops allow you to go through all combinations of elements in an arrays.

It can be used to simulate “array comprehension”. It’s a technique that allows you to create new arrays by iterating over existing ones and applying specific conditions or transformations to the elements. It’s like assembling a new collection from pieces of other collections based on certain rules.

Here’s how the do simulation works:

  1. Start the do simulation using the Do value
  2. Within the do simulation scope, you can use the bind function to define variables and bind them to Array values
  3. You can accumulate multiple bind statements to define multiple variables within the scope
  4. Inside the do simulation scope, you can also use the let function to define variables and bind them to simple values
  5. Regular Option functions like map and filter can still be used within the do simulation. These functions will receive the accumulated variables as arguments within the scope

Signature

export declare const Do: readonly {}[]

Example

import { Array as Arr, pipe } from "effect"
const doResult = pipe(
  Arr.Do,
  Arr.bind("x", () => [1, 3, 5]),
  Arr.bind("y", () => [2, 4, 6]),
  Arr.filter(({ x, y }) => x < y), // condition
  Arr.map(({ x, y }) => [x, y] as const) // transformation
)
assert.deepStrictEqual(doResult, [
  [1, 2],
  [1, 4],
  [1, 6],
  [3, 4],
  [3, 6],
  [5, 6]
])

// equivalent
const x = [1, 3, 5],
  y = [2, 4, 6],
  result = []
for (let i = 0; i < x.length; i++) {
  for (let j = 0; j < y.length; j++) {
    const _x = x[i],
      _y = y[j]
    if (_x < _y) result.push([_x, _y] as const)
  }
}

Added in v3.2.0

bind

The “do simulation” for array allows you to sequentially apply operations to the elements of arrays, just as nested loops allow you to go through all combinations of elements in an arrays.

It can be used to simulate “array comprehension”. It’s a technique that allows you to create new arrays by iterating over existing ones and applying specific conditions or transformations to the elements. It’s like assembling a new collection from pieces of other collections based on certain rules.

Here’s how the do simulation works:

  1. Start the do simulation using the Do value
  2. Within the do simulation scope, you can use the bind function to define variables and bind them to Array values
  3. You can accumulate multiple bind statements to define multiple variables within the scope
  4. Inside the do simulation scope, you can also use the let function to define variables and bind them to simple values
  5. Regular Option functions like map and filter can still be used within the do simulation. These functions will receive the accumulated variables as arguments within the scope

Signature

export declare const bind: {
  <A extends object, N extends string, B>(
    tag: Exclude<N, keyof A>,
    f: (a: A) => readonly B[]
  ): (self: readonly A[]) => { [K in N | keyof A]: K extends keyof A ? A[K] : B }[]
  <A extends object, N extends string, B>(
    self: readonly A[],
    tag: Exclude<N, keyof A>,
    f: (a: A) => readonly B[]
  ): { [K in N | keyof A]: K extends keyof A ? A[K] : B }[]
}

Example

import { Array as Arr, pipe } from "effect"
const doResult = pipe(
  Arr.Do,
  Arr.bind("x", () => [1, 3, 5]),
  Arr.bind("y", () => [2, 4, 6]),
  Arr.filter(({ x, y }) => x < y), // condition
  Arr.map(({ x, y }) => [x, y] as const) // transformation
)
assert.deepStrictEqual(doResult, [
  [1, 2],
  [1, 4],
  [1, 6],
  [3, 4],
  [3, 6],
  [5, 6]
])

// equivalent
const x = [1, 3, 5],
  y = [2, 4, 6],
  result = []
for (let i = 0; i < x.length; i++) {
  for (let j = 0; j < y.length; j++) {
    const _x = x[i],
      _y = y[j]
    if (_x < _y) result.push([_x, _y] as const)
  }
}

Added in v3.2.0

bindTo

The “do simulation” for array allows you to sequentially apply operations to the elements of arrays, just as nested loops allow you to go through all combinations of elements in an arrays.

It can be used to simulate “array comprehension”. It’s a technique that allows you to create new arrays by iterating over existing ones and applying specific conditions or transformations to the elements. It’s like assembling a new collection from pieces of other collections based on certain rules.

Here’s how the do simulation works:

  1. Start the do simulation using the Do value
  2. Within the do simulation scope, you can use the bind function to define variables and bind them to Array values
  3. You can accumulate multiple bind statements to define multiple variables within the scope
  4. Inside the do simulation scope, you can also use the let function to define variables and bind them to simple values
  5. Regular Option functions like map and filter can still be used within the do simulation. These functions will receive the accumulated variables as arguments within the scope

Signature

export declare const bindTo: {
  <N extends string>(tag: N): <A>(self: readonly A[]) => { [K in N]: A }[]
  <A, N extends string>(self: readonly A[], tag: N): { [K in N]: A }[]
}

Example

import { Array as Arr, pipe } from "effect"
const doResult = pipe(
  Arr.Do,
  Arr.bind("x", () => [1, 3, 5]),
  Arr.bind("y", () => [2, 4, 6]),
  Arr.filter(({ x, y }) => x < y), // condition
  Arr.map(({ x, y }) => [x, y] as const) // transformation
)
assert.deepStrictEqual(doResult, [
  [1, 2],
  [1, 4],
  [1, 6],
  [3, 4],
  [3, 6],
  [5, 6]
])

// equivalent
const x = [1, 3, 5],
  y = [2, 4, 6],
  result = []
for (let i = 0; i < x.length; i++) {
  for (let j = 0; j < y.length; j++) {
    const _x = x[i],
      _y = y[j]
    if (_x < _y) result.push([_x, _y] as const)
  }
}

Added in v3.2.0

let

The “do simulation” for array allows you to sequentially apply operations to the elements of arrays, just as nested loops allow you to go through all combinations of elements in an arrays.

It can be used to simulate “array comprehension”. It’s a technique that allows you to create new arrays by iterating over existing ones and applying specific conditions or transformations to the elements. It’s like assembling a new collection from pieces of other collections based on certain rules.

Here’s how the do simulation works:

  1. Start the do simulation using the Do value
  2. Within the do simulation scope, you can use the bind function to define variables and bind them to Array values
  3. You can accumulate multiple bind statements to define multiple variables within the scope
  4. Inside the do simulation scope, you can also use the let function to define variables and bind them to simple values
  5. Regular Option functions like map and filter can still be used within the do simulation. These functions will receive the accumulated variables as arguments within the scope

Signature

export declare const let: {
  <N extends string, B, A extends object>(
    tag: Exclude<N, keyof A>,
    f: (a: A) => B
  ): (self: readonly A[]) => { [K in N | keyof A]: K extends keyof A ? A[K] : B }[]
  <N extends string, A extends object, B>(
    self: readonly A[],
    tag: Exclude<N, keyof A>,
    f: (a: A) => B
  ): { [K in N | keyof A]: K extends keyof A ? A[K] : B }[]
}

Example

import { Array as Arr, pipe } from "effect"
const doResult = pipe(
  Arr.Do,
  Arr.bind("x", () => [1, 3, 5]),
  Arr.bind("y", () => [2, 4, 6]),
  Arr.filter(({ x, y }) => x < y), // condition
  Arr.map(({ x, y }) => [x, y] as const) // transformation
)
assert.deepStrictEqual(doResult, [
  [1, 2],
  [1, 4],
  [1, 6],
  [3, 4],
  [3, 6],
  [5, 6]
])

// equivalent
const x = [1, 3, 5],
  y = [2, 4, 6],
  result = []
for (let i = 0; i < x.length; i++) {
  for (let j = 0; j < y.length; j++) {
    const _x = x[i],
      _y = y[j]
    if (_x < _y) result.push([_x, _y] as const)
  }
}

Added in v3.2.0

elements

cartesian

Zips this chunk crosswise with the specified chunk.

Signature

export declare const cartesian: {
  <B>(that: readonly B[]): <A>(self: readonly A[]) => [A, B][]
  <A, B>(self: readonly A[], that: readonly B[]): [A, B][]
}

Example

import { Array } from "effect"

const array1 = [1, 2]
const array2 = ["a", "b"]
const product = Array.cartesian(array1, array2)
assert.deepStrictEqual(product, [
  [1, "a"],
  [1, "b"],
  [2, "a"],
  [2, "b"]
])

Added in v2.0.0

cartesianWith

Zips this chunk crosswise with the specified chunk using the specified combiner.

Signature

export declare const cartesianWith: {
  <A, B, C>(that: readonly B[], f: (a: A, b: B) => C): (self: readonly A[]) => C[]
  <A, B, C>(self: readonly A[], that: readonly B[], f: (a: A, b: B) => C): C[]
}

Example

import { Array } from "effect"

const array1 = [1, 2]
const array2 = ["a", "b"]
const product = Array.cartesianWith(array1, array2, (a, b) => `${a}-${b}`)
assert.deepStrictEqual(product, ["1-a", "1-b", "2-a", "2-b"])

Added in v2.0.0

contains

Returns a function that checks if a ReadonlyArray contains a given value using the default Equivalence.

Signature

export declare const contains: { <A>(a: A): (self: Iterable<A>) => boolean; <A>(self: Iterable<A>, a: A): boolean }

Example

import { Array } from "effect"

const letters = ["a", "b", "c", "d"]
const result = Array.contains("c")(letters)
assert.deepStrictEqual(result, true)

Added in v2.0.0

containsWith

Returns a function that checks if a ReadonlyArray contains a given value using a provided isEquivalent function.

Signature

export declare const containsWith: <A>(isEquivalent: (self: A, that: A) => boolean) => {
  (a: A): (self: Iterable<A>) => boolean
  (self: Iterable<A>, a: A): boolean
}

Example

import { Array } from "effect"

const numbers = [1, 2, 3, 4]
const isEquivalent = (a: number, b: number) => a === b
const containsNumber = Array.containsWith(isEquivalent)
const result = containsNumber(3)(numbers)
assert.deepStrictEqual(result, true)

Added in v2.0.0

every

Check if a predicate holds true for every ReadonlyArray element.

Signature

export declare const every: {
  <A, B extends A>(refinement: (a: NoInfer<A>, i: number) => a is B): (self: readonly A[]) => self is readonly B[]
  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: readonly A[]) => boolean
  <A, B extends A>(self: readonly A[], refinement: (a: A, i: number) => a is B): self is readonly B[]
  <A>(self: readonly A[], predicate: (a: A, i: number) => boolean): boolean
}

Added in v2.0.0

findFirst

Returns the first element that satisfies the specified predicate, or None if no such element exists.

Signature

export declare const findFirst: {
  <A, B>(f: (a: NoInfer<A>, i: number) => Option<B>): (self: Iterable<A>) => Option<B>
  <A, B extends A>(refinement: (a: NoInfer<A>, i: number) => a is B): (self: Iterable<A>) => Option<B>
  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => Option<A>
  <A, B>(self: Iterable<A>, f: (a: A, i: number) => Option<B>): Option<B>
  <A, B extends A>(self: Iterable<A>, refinement: (a: A, i: number) => a is B): Option<B>
  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Option<A>
}

Example

import { Array, Option } from "effect"

const numbers = [1, 2, 3, 4, 5]
const result = Array.findFirst(numbers, (x) => x > 3)
assert.deepStrictEqual(result, Option.some(4))

Added in v2.0.0

findFirstIndex

Return the first index for which a predicate holds.

Signature

export declare const findFirstIndex: {
  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => Option<number>
  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Option<number>
}

Example

import { Array, Option } from "effect"

const numbers = [5, 3, 8, 9]
const result = Array.findFirstIndex(numbers, (x) => x > 5)
assert.deepStrictEqual(result, Option.some(2))

Added in v2.0.0

findLast

Finds the last element in an iterable collection that satisfies the given predicate or refinement. Returns an Option containing the found element, or Option.none if no element matches.

Signature

export declare const findLast: {
  <A, B>(f: (a: NoInfer<A>, i: number) => Option<B>): (self: Iterable<A>) => Option<B>
  <A, B extends A>(refinement: (a: NoInfer<A>, i: number) => a is B): (self: Iterable<A>) => Option<B>
  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => Option<A>
  <A, B>(self: Iterable<A>, f: (a: A, i: number) => Option<B>): Option<B>
  <A, B extends A>(self: Iterable<A>, refinement: (a: A, i: number) => a is B): Option<B>
  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Option<A>
}

Example

import { Array, Option } from "effect"

const numbers = [1, 2, 3, 4, 5]
const result = Array.findLast(numbers, (n) => n % 2 === 0)
assert.deepStrictEqual(result, Option.some(4))

Added in v2.0.0

findLastIndex

Return the last index for which a predicate holds.

Signature

export declare const findLastIndex: {
  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => Option<number>
  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Option<number>
}

Example

import { Array, Option } from "effect"

const numbers = [1, 3, 8, 9]
const result = Array.findLastIndex(numbers, (x) => x < 5)
assert.deepStrictEqual(result, Option.some(1))

Added in v2.0.0

reverse

Reverse an Iterable, creating a new Array.

Signature

export declare const reverse: <S extends readonly [any, ...any[]] | Iterable<any>>(
  self: S
) => S extends readonly [infer A, ...(infer A)[]] ? [A, ...A[]] : S extends Iterable<infer A> ? A[] : never

Example

import { Array } from "effect"

const numbers = [1, 2, 3, 4]
const result = Array.reverse(numbers)
assert.deepStrictEqual(result, [4, 3, 2, 1])

Added in v2.0.0

some

Check if a predicate holds true for some ReadonlyArray element.

Signature

export declare const some: {
  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: readonly A[]) => self is readonly [A, ...A[]]
  <A>(self: readonly A[], predicate: (a: A, i: number) => boolean): self is readonly [A, ...A[]]
}

Added in v2.0.0

sortWith

Sorts an array based on a provided mapping function and order. The mapping function transforms the elements into a value that can be compared, and the order defines how those values should be sorted.

Signature

export declare const sortWith: {
  <S extends readonly [any, ...any[]] | Iterable<any>, B>(
    f: (a: ReadonlyArray.Infer<S>) => B,
    order: Order.Order<B>
  ): (self: S) => ReadonlyArray.With<S, ReadonlyArray.Infer<S>>
  <A, B>(self: readonly [A, ...A[]], f: (a: A) => B, O: Order.Order<B>): [A, ...A[]]
  <A, B>(self: Iterable<A>, f: (a: A) => B, order: Order.Order<B>): A[]
}

Example

import { Array, Order } from "effect"

const strings = ["aaa", "b", "cc"]
const result = Array.sortWith(strings, (s) => s.length, Order.number)
assert.deepStrictEqual(result, ["b", "cc", "aaa"])

// Explanation:
// The array of strings is sorted based on their lengths. The mapping function `(s) => s.length`
// converts each string into its length, and the `Order.number` specifies that the lengths should
// be sorted in ascending order.

Added in v2.0.0

filtering

filter

Signature

export declare const filter: {
  <A, B extends A>(refinement: (a: NoInfer<A>, i: number) => a is B): (self: Iterable<A>) => B[]
  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => A[]
  <A, B extends A>(self: Iterable<A>, refinement: (a: A, i: number) => a is B): B[]
  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): A[]
}

Added in v2.0.0

filterMap

Applies a function to each element of the Iterable and filters based on the result, keeping the transformed values where the function returns Some. This method combines filtering and mapping functionalities, allowing transformations and filtering of elements based on a single function pass.

Signature

export declare const filterMap: {
  <A, B>(f: (a: A, i: number) => Option<B>): (self: Iterable<A>) => B[]
  <A, B>(self: Iterable<A>, f: (a: A, i: number) => Option<B>): B[]
}

Example

import { Array, Option } from "effect"

const data = [1, 2, 3, 4, 5]
const evenSquares = (x: number) => (x % 2 === 0 ? Option.some(x * x) : Option.none())
const result = Array.filterMap(data, evenSquares)

assert.deepStrictEqual(result, [4, 16])

Added in v2.0.0

filterMapWhile

Applies a function to each element of the array and filters based on the result, stopping when a condition is not met. This method combines filtering and mapping in a single pass, and short-circuits, i.e., stops processing, as soon as the function returns None. This is useful when you need to transform an array but only up to the point where a certain condition holds true.

Signature

export declare const filterMapWhile: {
  <A, B>(f: (a: A, i: number) => Option<B>): (self: Iterable<A>) => B[]
  <A, B>(self: Iterable<A>, f: (a: A, i: number) => Option<B>): B[]
}

Example

import { Array, Option } from "effect"

const data = [2, 4, 5]
const toSquareTillOdd = (x: number) => (x % 2 === 0 ? Option.some(x * x) : Option.none())
const result = Array.filterMapWhile(data, toSquareTillOdd)

assert.deepStrictEqual(result, [4, 16])

Added in v2.0.0

getLefts

Retrieves the Left values from an Iterable of Eithers, collecting them into an array.

Signature

export declare const getLefts: <T extends Iterable<array_<any, any>>>(self: T) => array_.Left<ReadonlyArray.Infer<T>>[]

Example

import { Array, Either } from "effect"

assert.deepStrictEqual(Array.getLefts([Either.right(1), Either.left("err"), Either.right(2)]), ["err"])

Added in v2.0.0

getRights

Retrieves the Right values from an Iterable of Eithers, collecting them into an array.

Signature

export declare const getRights: <T extends Iterable<array_<any, any>>>(
  self: T
) => array_.Right<ReadonlyArray.Infer<T>>[]

Example

import { Array, Either } from "effect"

assert.deepStrictEqual(Array.getRights([Either.right(1), Either.left("err"), Either.right(2)]), [1, 2])

Added in v2.0.0

getSomes

Retrieves the Some values from an Iterable of Options, collecting them into an array.

Signature

export declare const getSomes: <T extends Iterable<Option<X>>, X = any>(
  self: T
) => Option.Value<ReadonlyArray.Infer<T>>[]

Example

import { Array, Option } from "effect"

assert.deepStrictEqual(Array.getSomes([Option.some(1), Option.none(), Option.some(2)]), [1, 2])

Added in v2.0.0

partition

Separate elements based on a predicate that also exposes the index of the element.

Signature

export declare const partition: {
  <A, B extends A>(
    refinement: (a: NoInfer<A>, i: number) => a is B
  ): (self: Iterable<A>) => [excluded: Exclude<A, B>[], satisfying: B[]]
  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => [excluded: A[], satisfying: A[]]
  <A, B extends A>(
    self: Iterable<A>,
    refinement: (a: A, i: number) => a is B
  ): [excluded: Exclude<A, B>[], satisfying: B[]]
  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): [excluded: A[], satisfying: A[]]
}

Added in v2.0.0

partitionMap

Applies a function to each element of the Iterable, categorizing the results into two separate arrays. This function is particularly useful for operations where each element can result in two possible types, and you want to separate these types into different collections. For instance, separating validation results into successes and failures.

Signature

export declare const partitionMap: {
  <A, B, C>(f: (a: A, i: number) => array_<C, B>): (self: Iterable<A>) => [left: B[], right: C[]]
  <A, B, C>(self: Iterable<A>, f: (a: A, i: number) => array_<C, B>): [left: B[], right: C[]]
}

Example

import { Array, Either } from "effect"

const data = [1, 2, 3, 4, 5]
const isEven = (x: number) => x % 2 === 0
const partitioned = Array.partitionMap(data, (x) => (isEven(x) ? Either.right(x) : Either.left(x)))

assert.deepStrictEqual(partitioned, [
  [1, 3, 5],
  [2, 4]
])

Added in v2.0.0

separate

Separates an Iterable into two arrays based on a predicate.

Signature

export declare const separate: <T extends Iterable<array_<any, any>>>(
  self: T
) => [array_.Left<ReadonlyArray.Infer<T>>[], array_.Right<ReadonlyArray.Infer<T>>[]]

Example

import { Array } from "effect"

const numbers = [1, 2, 3, 4]
const result = Array.partition(numbers, (n) => n % 2 === 0)
assert.deepStrictEqual(result, [
  [1, 3],
  [2, 4]
])

Added in v2.0.0

folding

join

Joins the elements together with “sep” in the middle.

Signature

export declare const join: {
  (sep: string): (self: Iterable<string>) => string
  (self: Iterable<string>, sep: string): string
}

Example

import { Array } from "effect"

const strings = ["a", "b", "c"]
const joined = Array.join(strings, "-")
assert.deepStrictEqual(joined, "a-b-c")

Added in v2.0.0

mapAccum

Statefully maps over the chunk, producing new elements of type B.

Signature

export declare const mapAccum: {
  <S, A, B>(s: S, f: (s: S, a: A, i: number) => readonly [S, B]): (self: Iterable<A>) => [state: S, mappedArray: B[]]
  <S, A, B>(self: Iterable<A>, s: S, f: (s: S, a: A, i: number) => readonly [S, B]): [state: S, mappedArray: B[]]
}

Example

import { Array } from "effect"

const numbers = [1, 2, 3]
const result = Array.mapAccum(numbers, 0, (acc, n) => [acc + n, acc + n])
assert.deepStrictEqual(result, [6, [1, 3, 6]])

Added in v2.0.0

reduce

Reduces an array from the left.

Signature

export declare const reduce: {
  <B, A>(b: B, f: (b: B, a: A, i: number) => B): (self: Iterable<A>) => B
  <A, B>(self: Iterable<A>, b: B, f: (b: B, a: A, i: number) => B): B
}

Example

import { Array } from "effect"

const numbers = [1, 2, 3]
const result = Array.reduce(numbers, 0, (acc, n) => acc + n)
assert.deepStrictEqual(result, 6)

Added in v2.0.0

reduceRight

Reduces an array from the right.

Signature

export declare const reduceRight: {
  <B, A>(b: B, f: (b: B, a: A, i: number) => B): (self: Iterable<A>) => B
  <A, B>(self: Iterable<A>, b: B, f: (b: B, a: A, i: number) => B): B
}

Example

import { Array } from "effect"

const numbers = [1, 2, 3]
const result = Array.reduceRight(numbers, 0, (acc, n) => acc + n)
assert.deepStrictEqual(result, 6)

Added in v2.0.0

scan

Accumulates values from an Iterable starting from the left, storing each intermediate result in an array. Useful for tracking the progression of a value through a series of transformations.

Signature

export declare const scan: {
  <B, A>(b: B, f: (b: B, a: A) => B): (self: Iterable<A>) => [B, ...B[]]
  <A, B>(self: Iterable<A>, b: B, f: (b: B, a: A) => B): [B, ...B[]]
}

Example

import { Array } from "effect"

const numbers = [1, 2, 3, 4]
const result = Array.scan(numbers, 0, (acc, value) => acc + value)
assert.deepStrictEqual(result, [0, 1, 3, 6, 10])

// Explanation:
// This function starts with the initial value (0 in this case)
// and adds each element of the array to this accumulator one by one,
// keeping track of the cumulative sum after each addition.
// Each of these sums is captured in the resulting array.

Added in v2.0.0

scanRight

Accumulates values from an Iterable starting from the right, storing each intermediate result in an array. Useful for tracking the progression of a value through a series of transformations.

Signature

export declare const scanRight: {
  <B, A>(b: B, f: (b: B, a: A) => B): (self: Iterable<A>) => [B, ...B[]]
  <A, B>(self: Iterable<A>, b: B, f: (b: B, a: A) => B): [B, ...B[]]
}

Example

import { Array } from "effect"

const numbers = [1, 2, 3, 4]
const result = Array.scanRight(numbers, 0, (acc, value) => acc + value)
assert.deepStrictEqual(result, [10, 9, 7, 4, 0])

Added in v2.0.0

getters

drop

Drop a max number of elements from the start of an Iterable, creating a new Array.

Note. n is normalized to a non negative integer.

Signature

export declare const drop: { (n: number): <A>(self: Iterable<A>) => A[]; <A>(self: Iterable<A>, n: number): A[] }

Example

import { Array } from "effect"

const numbers = [1, 2, 3, 4, 5]
const result = Array.drop(numbers, 2)
assert.deepStrictEqual(result, [3, 4, 5])

Added in v2.0.0

dropRight

Drop a max number of elements from the end of an Iterable, creating a new Array.

Note. n is normalized to a non negative integer.

Signature

export declare const dropRight: { (n: number): <A>(self: Iterable<A>) => A[]; <A>(self: Iterable<A>, n: number): A[] }

Example

import { Array } from "effect"

const numbers = [1, 2, 3, 4, 5]
const result = Array.dropRight(numbers, 2)
assert.deepStrictEqual(result, [1, 2, 3])

Added in v2.0.0

dropWhile

Remove the longest initial subarray for which all element satisfy the specified predicate, creating a new Array.

Signature

export declare const dropWhile: {
  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => A[]
  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): A[]
}

Example

import { Array } from "effect"

const numbers = [1, 2, 3, 4, 5]
const result = Array.dropWhile(numbers, (x) => x < 4)
assert.deepStrictEqual(result, [4, 5])

Added in v2.0.0

get

This function provides a safe way to read a value at a particular index from a ReadonlyArray.

Signature

export declare const get: {
  (index: number): <A>(self: readonly A[]) => Option<A>
  <A>(self: readonly A[], index: number): Option<A>
}

Added in v2.0.0

Get the first element of a ReadonlyArray, or None if the ReadonlyArray is empty.

Signature

export declare const head: <A>(self: readonly A[]) => Option<A>

Added in v2.0.0

headNonEmpty

Get the first element of a non empty array.

Signature

export declare const headNonEmpty: <A>(self: readonly [A, ...A[]]) => A

Example

import { Array } from "effect"

const result = Array.headNonEmpty([1, 2, 3, 4])
assert.deepStrictEqual(result, 1)

Added in v2.0.0

init

Get all but the last element of an Iterable, creating a new Array, or None if the Iterable is empty.

Signature

export declare const init: <A>(self: Iterable<A>) => Option<A[]>

Added in v2.0.0

initNonEmpty

Get all but the last element of a non empty array, creating a new array.

Signature

export declare const initNonEmpty: <A>(self: readonly [A, ...A[]]) => A[]

Example

import { Array } from "effect"

const result = Array.initNonEmpty([1, 2, 3, 4])
assert.deepStrictEqual(result, [1, 2, 3])

Added in v2.0.0

last

Get the last element in a ReadonlyArray, or None if the ReadonlyArray is empty.

Signature

export declare const last: <A>(self: readonly A[]) => Option<A>

Added in v2.0.0

lastNonEmpty

Get the last element of a non empty array.

Signature

export declare const lastNonEmpty: <A>(self: readonly [A, ...A[]]) => A

Example

import { Array } from "effect"

const result = Array.lastNonEmpty([1, 2, 3, 4])
assert.deepStrictEqual(result, 4)

Added in v2.0.0

length

Return the number of elements in a ReadonlyArray.

Signature

export declare const length: <A>(self: readonly A[]) => number

Added in v2.0.0

tail

Get all but the first element of an Iterable, creating a new Array, or None if the Iterable is empty.

Signature

export declare const tail: <A>(self: Iterable<A>) => Option<A[]>

Added in v2.0.0

tailNonEmpty

Get all but the first element of a NonEmptyReadonlyArray.

Signature

export declare const tailNonEmpty: <A>(self: readonly [A, ...A[]]) => A[]

Example

import { Array } from "effect"

const result = Array.tailNonEmpty([1, 2, 3, 4])
assert.deepStrictEqual(result, [2, 3, 4])

Added in v2.0.0

take

Keep only a max number of elements from the start of an Iterable, creating a new Array.

Note. n is normalized to a non negative integer.

Signature

export declare const take: { (n: number): <A>(self: Iterable<A>) => A[]; <A>(self: Iterable<A>, n: number): A[] }

Example

import { Array } from "effect"

const numbers = [1, 2, 3, 4, 5]
const result = Array.take(numbers, 3)
assert.deepStrictEqual(result, [1, 2, 3])

Added in v2.0.0

takeRight

Keep only a max number of elements from the end of an Iterable, creating a new Array.

Note. n is normalized to a non negative integer.

Signature

export declare const takeRight: { (n: number): <A>(self: Iterable<A>) => A[]; <A>(self: Iterable<A>, n: number): A[] }

Example

import { Array } from "effect"

const numbers = [1, 2, 3, 4, 5]
const result = Array.takeRight(numbers, 3)
assert.deepStrictEqual(result, [3, 4, 5])

Added in v2.0.0

takeWhile

Calculate the longest initial subarray for which all element satisfy the specified predicate, creating a new Array.

Signature

export declare const takeWhile: {
  <A, B extends A>(refinement: (a: NoInfer<A>, i: number) => a is B): (self: Iterable<A>) => B[]
  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => A[]
  <A, B extends A>(self: Iterable<A>, refinement: (a: A, i: number) => a is B): B[]
  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): A[]
}

Example

import { Array } from "effect"

const numbers = [1, 3, 2, 4, 1, 2]
const result = Array.takeWhile(numbers, (x) => x < 4)
assert.deepStrictEqual(result, [1, 3, 2])

// Explanation:
// - The function starts with the first element (`1`), which is less than `4`, so it adds `1` to the result.
// - The next element (`3`) is also less than `4`, so it adds `3`.
// - The next element (`2`) is again less than `4`, so it adds `2`.
// - The function then encounters `4`, which is not less than `4`. At this point, it stops checking further elements and finalizes the result.

Added in v2.0.0

grouping

group

Group equal, consecutive elements of a NonEmptyReadonlyArray into NonEmptyArrays.

Signature

export declare const group: <A>(self: readonly [A, ...A[]]) => [[A, ...A[]], ...[A, ...A[]][]]

Example

import { Array } from "effect"

const result = Array.group([1, 1, 2, 2, 2, 3, 1])
assert.deepStrictEqual(result, [[1, 1], [2, 2, 2], [3], [1]])

Added in v2.0.0

groupBy

Splits an Iterable into sub-non-empty-arrays stored in an object, based on the result of calling a string-returning function on each element, and grouping the results according to values returned

Signature

export declare const groupBy: {
  <A, K extends string | symbol>(
    f: (a: A) => K
  ): (self: Iterable<A>) => Record<Record.ReadonlyRecord.NonLiteralKey<K>, [A, ...A[]]>
  <A, K extends string | symbol>(
    self: Iterable<A>,
    f: (a: A) => K
  ): Record<Record.ReadonlyRecord.NonLiteralKey<K>, [A, ...A[]]>
}

Example

import { Array } from "effect"

const people = [
  { name: "Alice", group: "A" },
  { name: "Bob", group: "B" },
  { name: "Charlie", group: "A" }
]
const result = Array.groupBy(people, (person) => person.group)
assert.deepStrictEqual(result, {
  A: [
    { name: "Alice", group: "A" },
    { name: "Charlie", group: "A" }
  ],
  B: [{ name: "Bob", group: "B" }]
})

Added in v2.0.0

groupWith

Group equal, consecutive elements of a NonEmptyReadonlyArray into NonEmptyArrays using the provided isEquivalent function.

Signature

export declare const groupWith: {
  <A>(isEquivalent: (self: A, that: A) => boolean): (self: readonly [A, ...A[]]) => [[A, ...A[]], ...[A, ...A[]][]]
  <A>(self: readonly [A, ...A[]], isEquivalent: (self: A, that: A) => boolean): [[A, ...A[]], ...[A, ...A[]][]]
}

Example

import { Array } from "effect"

const result = Array.groupWith(["a", "a", "b", "b", "b", "c", "a"], (x, y) => x === y)
assert.deepStrictEqual(result, [["a", "a"], ["b", "b", "b"], ["c"], ["a"]])

Added in v2.0.0

guards

isArray

Determine if unknown is an Array.

Signature

export declare const isArray: { (self: unknown): self is unknown[]; <T>(self: T): self is Extract<T, readonly any[]> }

Example

import { isArray } from "effect/Array"

assert.deepStrictEqual(isArray(null), false)
assert.deepStrictEqual(isArray([1, 2, 3]), true)

Added in v2.0.0

isEmptyArray

Determine if an Array is empty narrowing down the type to [].

Signature

export declare const isEmptyArray: <A>(self: A[]) => self is []

Example

import { isEmptyArray } from "effect/Array"

assert.deepStrictEqual(isEmptyArray([]), true)
assert.deepStrictEqual(isEmptyArray([1, 2, 3]), false)

Added in v2.0.0

isEmptyReadonlyArray

Determine if a ReadonlyArray is empty narrowing down the type to readonly [].

Signature

export declare const isEmptyReadonlyArray: <A>(self: readonly A[]) => self is readonly []

Example

import { isEmptyReadonlyArray } from "effect/Array"

assert.deepStrictEqual(isEmptyReadonlyArray([]), true)
assert.deepStrictEqual(isEmptyReadonlyArray([1, 2, 3]), false)

Added in v2.0.0

isNonEmptyArray

Determine if an Array is non empty narrowing down the type to NonEmptyArray.

An Array is considered to be a NonEmptyArray if it contains at least one element.

Signature

export declare const isNonEmptyArray: <A>(self: A[]) => self is [A, ...A[]]

Example

import { isNonEmptyArray } from "effect/Array"

assert.deepStrictEqual(isNonEmptyArray([]), false)
assert.deepStrictEqual(isNonEmptyArray([1, 2, 3]), true)

Added in v2.0.0

isNonEmptyReadonlyArray

Determine if a ReadonlyArray is non empty narrowing down the type to NonEmptyReadonlyArray.

A ReadonlyArray is considered to be a NonEmptyReadonlyArray if it contains at least one element.

Signature

export declare const isNonEmptyReadonlyArray: <A>(self: readonly A[]) => self is readonly [A, ...A[]]

Example

import { isNonEmptyReadonlyArray } from "effect/Array"

assert.deepStrictEqual(isNonEmptyReadonlyArray([]), false)
assert.deepStrictEqual(isNonEmptyReadonlyArray([1, 2, 3]), true)

Added in v2.0.0

instances

getEquivalence

Creates an equivalence relation for arrays.

Signature

export declare const getEquivalence: <A>(
  isEquivalent: Equivalence.Equivalence<A>
) => Equivalence.Equivalence<readonly A[]>

Example

import { Array } from "effect"

const numbers1 = [1, 2, 3]
const numbers2 = [1, 2, 3]
const eq = Array.getEquivalence<number>((a, b) => a === b)
assert.deepStrictEqual(eq(numbers1, numbers2), true)

Added in v2.0.0

getOrder

This function creates and returns a new Order for an array of values based on a given Order for the elements of the array. The returned Order compares two arrays by applying the given Order to each element in the arrays. If all elements are equal, the arrays are then compared based on their length. It is useful when you need to compare two arrays of the same type and you have a specific way of comparing each element of the array.

Signature

export declare const getOrder: <A>(O: Order.Order<A>) => Order.Order<readonly A[]>

Added in v2.0.0

lifting

liftEither

Lifts a function that returns an Either into a function that returns an array. If the Either is a left, it returns an empty array. If the Either is a right, it returns an array with the right value.

Signature

export declare const liftEither: <A extends unknown[], E, B>(f: (...a: A) => array_<B, E>) => (...a: A) => B[]

Example

import { Array, Either } from "effect"

const parseNumber = (s: string): Either.Either<number, Error> =>
  isNaN(Number(s)) ? Either.left(new Error("Not a number")) : Either.right(Number(s))

const liftedParseNumber = Array.liftEither(parseNumber)

const result1 = liftedParseNumber("42")
assert.deepStrictEqual(result1, [42])

const result2 = liftedParseNumber("not a number")
assert.deepStrictEqual(result2, [])

// Explanation:
// The function parseNumber is lifted to return an array.
// When parsing "42", it returns an Either.left with the number 42, resulting in [42].
// When parsing "not a number", it returns an Either.right with an error, resulting in an empty array [].

Added in v2.0.0

liftNullable

Signature

export declare const liftNullable: <A extends unknown[], B>(
  f: (...a: A) => B | null | undefined
) => (...a: A) => NonNullable<B>[]

Added in v2.0.0

liftOption

Signature

export declare const liftOption: <A extends unknown[], B>(f: (...a: A) => Option<B>) => (...a: A) => B[]

Added in v2.0.0

liftPredicate

Lifts a predicate into an array.

Signature

export declare const liftPredicate: {
  <A, B extends A>(refinement: Refinement<A, B>): (a: A) => B[]
  <A>(predicate: Predicate<A>): <B extends A>(b: B) => B[]
}

Example

import { Array } from "effect"

const isEven = (n: number) => n % 2 === 0
const to = Array.liftPredicate(isEven)
assert.deepStrictEqual(to(1), [])
assert.deepStrictEqual(to(2), [2])

Added in v2.0.0

mapping

map

Signature

export declare const map: {
  <S extends readonly any[], B>(f: (a: ReadonlyArray.Infer<S>, i: number) => B): (self: S) => ReadonlyArray.With<S, B>
  <S extends readonly any[], B>(self: S, f: (a: ReadonlyArray.Infer<S>, i: number) => B): ReadonlyArray.With<S, B>
}

Added in v2.0.0

models

NonEmptyArray (type alias)

Signature

export type NonEmptyArray<A> = [A, ...Array<A>]

Added in v2.0.0

NonEmptyReadonlyArray (type alias)

Signature

export type NonEmptyReadonlyArray<A> = readonly [A, ...Array<A>]

Added in v2.0.0

pattern matching

match

Matches the elements of an array, applying functions to cases of empty and non-empty arrays.

Signature

export declare const match: {
  <B, A, C = B>(options: {
    readonly onEmpty: LazyArg<B>
    readonly onNonEmpty: (self: readonly [A, ...A[]]) => C
  }): (self: readonly A[]) => B | C
  <A, B, C = B>(
    self: readonly A[],
    options: { readonly onEmpty: LazyArg<B>; readonly onNonEmpty: (self: readonly [A, ...A[]]) => C }
  ): B | C
}

Example

import { Array } from "effect"

const match = Array.match({
  onEmpty: () => "empty",
  onNonEmpty: ([head, ...tail]) => `head: ${head}, tail: ${tail.length}`
})
assert.deepStrictEqual(match([]), "empty")
assert.deepStrictEqual(match([1, 2, 3]), "head: 1, tail: 2")

Added in v2.0.0

matchLeft

Matches the elements of an array from the left, applying functions to cases of empty and non-empty arrays.

Signature

export declare const matchLeft: {
  <B, A, C = B>(options: {
    readonly onEmpty: LazyArg<B>
    readonly onNonEmpty: (head: A, tail: A[]) => C
  }): (self: readonly A[]) => B | C
  <A, B, C = B>(
    self: readonly A[],
    options: { readonly onEmpty: LazyArg<B>; readonly onNonEmpty: (head: A, tail: A[]) => C }
  ): B | C
}

Example

import { Array } from "effect"

const matchLeft = Array.matchLeft({
  onEmpty: () => "empty",
  onNonEmpty: (head, tail) => `head: ${head}, tail: ${tail.length}`
})
assert.deepStrictEqual(matchLeft([]), "empty")
assert.deepStrictEqual(matchLeft([1, 2, 3]), "head: 1, tail: 2")

Added in v2.0.0

matchRight

Matches the elements of an array from the right, applying functions to cases of empty and non-empty arrays.

Signature

export declare const matchRight: {
  <B, A, C = B>(options: {
    readonly onEmpty: LazyArg<B>
    readonly onNonEmpty: (init: A[], last: A) => C
  }): (self: readonly A[]) => B | C
  <A, B, C = B>(
    self: readonly A[],
    options: { readonly onEmpty: LazyArg<B>; readonly onNonEmpty: (init: A[], last: A) => C }
  ): B | C
}

Example

import { Array } from "effect"

const matchRight = Array.matchRight({
  onEmpty: () => "empty",
  onNonEmpty: (init, last) => `init: ${init.length}, last: ${last}`
})
assert.deepStrictEqual(matchRight([]), "empty")
assert.deepStrictEqual(matchRight([1, 2, 3]), "init: 2, last: 3")

Added in v2.0.0

sequencing

flatMap

Applies a function to each element in an array and returns a new array containing the concatenated mapped elements.

Signature

export declare const flatMap: {
  <S extends readonly any[], T extends readonly any[]>(
    f: (a: ReadonlyArray.Infer<S>, i: number) => T
  ): (self: S) => ReadonlyArray.AndNonEmpty<S, T, ReadonlyArray.Infer<T>>
  <A, B>(self: readonly [A, ...A[]], f: (a: A, i: number) => readonly [B, ...B[]]): [B, ...B[]]
  <A, B>(self: readonly A[], f: (a: A, i: number) => readonly B[]): B[]
}

Added in v2.0.0

flatMapNullable

Maps over an array and flattens the result, removing null and undefined values.

Signature

export declare const flatMapNullable: {
  <A, B>(f: (a: A) => B | null | undefined): (self: readonly A[]) => NonNullable<B>[]
  <A, B>(self: readonly A[], f: (a: A) => B | null | undefined): NonNullable<B>[]
}

Example

import { Array } from "effect"

const numbers = [1, 2, 3]
const result = Array.flatMapNullable(numbers, (n) => (n % 2 === 0 ? null : n))
assert.deepStrictEqual(result, [1, 3])

// Explanation:
// The array of numbers [1, 2, 3] is mapped with a function that returns null for even numbers
// and the number itself for odd numbers. The resulting array [1, null, 3] is then flattened
// to remove null values, resulting in [1, 3].

Added in v2.0.0

flatten

Combines multiple arrays into a single array by concatenating all elements from each nested array. This function ensures that the structure of nested arrays is collapsed into a single, flat array.

Signature

export declare const flatten: <S extends readonly (readonly any[])[]>(self: S) => ReadonlyArray.Flatten<S>

Example

import { Array } from "effect"

const nestedArrays = [[1, 2], [], [3, 4], [], [5, 6]]
const result = Array.flatten(nestedArrays)

assert.deepStrictEqual(result, [1, 2, 3, 4, 5, 6])

Added in v2.0.0

sorting

sort

Create a new array with elements sorted in increasing order based on the specified comparator. If the input is a NonEmptyReadonlyArray, the output will also be a NonEmptyReadonlyArray.

Signature

export declare const sort: {
  <B>(
    O: Order.Order<B>
  ): <A extends B, S extends readonly A[] | Iterable<A>>(self: S) => ReadonlyArray.With<S, ReadonlyArray.Infer<S>>
  <A extends B, B>(self: readonly [A, ...A[]], O: Order.Order<B>): [A, ...A[]]
  <A extends B, B>(self: Iterable<A>, O: Order.Order<B>): A[]
}

Added in v2.0.0

sortBy

Sorts the elements of an Iterable in increasing order based on the provided orders. The elements are compared using the first order in orders, then the second order if the first comparison is equal, and so on.

Signature

export declare const sortBy: <S extends readonly [any, ...any[]] | Iterable<any>>(
  ...orders: readonly Order.Order<ReadonlyArray.Infer<S>>[]
) => (self: S) => S extends readonly [infer A, ...(infer A)[]] ? [A, ...A[]] : S extends Iterable<infer A> ? A[] : never

Example

import { Array, Order } from "effect"

const users = [
  { name: "Alice", age: 30 },
  { name: "Bob", age: 25 },
  { name: "Charlie", age: 30 }
]

const result = Array.sortBy(
  Order.mapInput(Order.number, (user: (typeof users)[number]) => user.age),
  Order.mapInput(Order.string, (user: (typeof users)[number]) => user.name)
)(users)

assert.deepStrictEqual(result, [
  { name: "Bob", age: 25 },
  { name: "Alice", age: 30 },
  { name: "Charlie", age: 30 }
])

// Explanation:
// The array of users is sorted first by age in ascending order. When ages are equal,
// the users are further sorted by name in ascending order.

Added in v2.0.0

splitting

chunksOf

Splits an Iterable into length-n pieces. The last piece will be shorter if n does not evenly divide the length of the Iterable. Note that chunksOf(n)([]) is [], not [[]]. This is intentional, and is consistent with a recursive definition of chunksOf; it satisfies the property that

chunksOf(n)(xs).concat(chunksOf(n)(ys)) == chunksOf(n)(xs.concat(ys)))

whenever n evenly divides the length of self.

Signature

export declare const chunksOf: {
  (
    n: number
  ): <S extends Iterable<any>>(self: S) => ReadonlyArray.With<S, [ReadonlyArray.Infer<S>, ...ReadonlyArray.Infer<S>[]]>
  <A>(self: readonly [A, ...A[]], n: number): [[A, ...A[]], ...[A, ...A[]][]]
  <A>(self: Iterable<A>, n: number): [A, ...A[]][]
}

Example

import { Array } from "effect"

const numbers = [1, 2, 3, 4, 5]
const result = Array.chunksOf(numbers, 2)
assert.deepStrictEqual(result, [[1, 2], [3, 4], [5]])

// Explanation:
// The `chunksOf` function takes an array of numbers `[1, 2, 3, 4, 5]` and a number `2`.
// It splits the array into chunks of length 2. Since the array length is not evenly divisible by 2,
// the last chunk contains the remaining elements.
// The result is `[[1, 2], [3, 4], [5]]`.

Added in v2.0.0

span

Split an Iterable into two parts:

  1. the longest initial subarray for which all elements satisfy the specified predicate
  2. the remaining elements

Signature

export declare const span: {
  <A, B extends A>(
    refinement: (a: NoInfer<A>, i: number) => a is B
  ): (self: Iterable<A>) => [init: B[], rest: Exclude<A, B>[]]
  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => [init: A[], rest: A[]]
  <A, B extends A>(self: Iterable<A>, refinement: (a: A, i: number) => a is B): [init: B[], rest: Exclude<A, B>[]]
  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): [init: A[], rest: A[]]
}

Added in v2.0.0

split

Splits this iterable into n equally sized arrays.

Signature

export declare const split: { (n: number): <A>(self: Iterable<A>) => A[][]; <A>(self: Iterable<A>, n: number): A[][] }

Example

import { Array } from "effect"

const numbers = [1, 2, 3, 4, 5, 6, 7, 8]
const result = Array.split(numbers, 3)
assert.deepStrictEqual(result, [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8]
])

Added in v2.0.0

splitAt

Splits an Iterable into two segments, with the first segment containing a maximum of n elements. The value of n can be 0.

Signature

export declare const splitAt: {
  (n: number): <A>(self: Iterable<A>) => [beforeIndex: A[], fromIndex: A[]]
  <A>(self: Iterable<A>, n: number): [beforeIndex: A[], fromIndex: A[]]
}

Example

import { Array } from "effect"

const numbers = [1, 2, 3, 4, 5]
const result = Array.splitAt(numbers, 3)
assert.deepStrictEqual(result, [
  [1, 2, 3],
  [4, 5]
])

Added in v2.0.0

splitNonEmptyAt

Splits a NonEmptyReadonlyArray into two segments, with the first segment containing a maximum of n elements. The value of n must be >= 1.

Signature

export declare const splitNonEmptyAt: {
  (n: number): <A>(self: readonly [A, ...A[]]) => [beforeIndex: [A, ...A[]], fromIndex: A[]]
  <A>(self: readonly [A, ...A[]], n: number): [beforeIndex: [A, ...A[]], fromIndex: A[]]
}

Example

import { Array } from "effect"

const result = Array.splitNonEmptyAt(["a", "b", "c", "d", "e"], 3)
assert.deepStrictEqual(result, [
  ["a", "b", "c"],
  ["d", "e"]
])

Added in v2.0.0

splitWhere

Splits this iterable on the first element that matches this predicate. Returns a tuple containing two arrays: the first one is before the match, and the second one is from the match onward.

Signature

export declare const splitWhere: {
  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => [beforeMatch: A[], fromMatch: A[]]
  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): [beforeMatch: A[], fromMatch: A[]]
}

Example

import { Array } from "effect"

const numbers = [1, 2, 3, 4, 5]
const result = Array.splitWhere(numbers, (n) => n > 3)
assert.deepStrictEqual(result, [
  [1, 2, 3],
  [4, 5]
])

Added in v2.0.0

unappend

Return a tuple containing a copy of the NonEmptyReadonlyArray without its last element, and that last element.

Signature

export declare const unappend: <A>(self: readonly [A, ...A[]]) => [arrayWithoutLastElement: A[], lastElement: A]

Example

import { Array } from "effect"

const result = Array.unappend([1, 2, 3, 4])
assert.deepStrictEqual(result, [[1, 2, 3], 4])

Added in v2.0.0

unprepend

Return a tuple containing the first element, and a new Array of the remaining elements, if any.

Signature

export declare const unprepend: <A>(self: readonly [A, ...A[]]) => [firstElement: A, remainingElements: A[]]

Example

import { Array } from "effect"

const result = Array.unprepend([1, 2, 3, 4])
assert.deepStrictEqual(result, [1, [2, 3, 4]])

Added in v2.0.0

type lambdas

ReadonlyArrayTypeLambda (interface)

Signature

export interface ReadonlyArrayTypeLambda extends TypeLambda {
  readonly type: ReadonlyArray<this["Target"]>
}

Added in v2.0.0

unsafe

unsafeGet

Gets an element unsafely, will throw on out of bounds.

Signature

export declare const unsafeGet: {
  (index: number): <A>(self: readonly A[]) => A
  <A>(self: readonly A[], index: number): A
}

Added in v2.0.0

utils

ReadonlyArray (namespace)

Added in v2.0.0

AndNonEmpty (type alias)

Signature

export type AndNonEmpty<S extends Iterable<any>, T extends Iterable<any>, A> =
  S extends NonEmptyReadonlyArray<any> ? (T extends NonEmptyReadonlyArray<any> ? NonEmptyArray<A> : Array<A>) : Array<A>

Added in v2.0.0

Flatten (type alias)

Signature

export type Flatten<T extends ReadonlyArray<ReadonlyArray<any>>> =
  T extends NonEmptyReadonlyArray<NonEmptyReadonlyArray<infer A>>
    ? NonEmptyArray<A>
    : T extends ReadonlyArray<ReadonlyArray<infer A>>
      ? Array<A>
      : never

Added in v2.0.0

Infer (type alias)

Signature

export type Infer<S extends Iterable<any>> =
  S extends ReadonlyArray<infer A> ? A : S extends Iterable<infer A> ? A : never

Added in v2.0.0

OrNonEmpty (type alias)

Signature

export type OrNonEmpty<S extends Iterable<any>, T extends Iterable<any>, A> =
  S extends NonEmptyReadonlyArray<any>
    ? NonEmptyArray<A>
    : T extends NonEmptyReadonlyArray<any>
      ? NonEmptyArray<A>
      : Array<A>

Added in v2.0.0

With (type alias)

Signature

export type With<S extends Iterable<any>, A> = S extends NonEmptyReadonlyArray<any> ? NonEmptyArray<A> : Array<A>

Added in v2.0.0

chop

A useful recursion pattern for processing an Iterable to produce a new Array, often used for “chopping” up the input Iterable. Typically chop is called with some function that will consume an initial prefix of the Iterable and produce a value and the rest of the Array.

Signature

export declare const chop: {
  <S extends Iterable<any>, B>(
    f: (
      as: readonly [ReadonlyArray.Infer<S>, ...ReadonlyArray.Infer<S>[]]
    ) => readonly [B, readonly ReadonlyArray.Infer<S>[]]
  ): (self: S) => ReadonlyArray.With<S, ReadonlyArray.Infer<S>>
  <A, B>(self: readonly [A, ...A[]], f: (as: readonly [A, ...A[]]) => readonly [B, readonly A[]]): [B, ...B[]]
  <A, B>(self: Iterable<A>, f: (as: readonly [A, ...A[]]) => readonly [B, readonly A[]]): B[]
}

Example

import { Array } from "effect"

const numbers = [1, 2, 3, 4, 5]
const result = Array.chop(numbers, (as): [number, Array<number>] => [as[0] * 2, as.slice(1)])
assert.deepStrictEqual(result, [2, 4, 6, 8, 10])

// Explanation:
// The `chopFunction` takes the first element of the array, doubles it, and then returns it along with the rest of the array.
// The `chop` function applies this `chopFunction` recursively to the input array `[1, 2, 3, 4, 5]`,
// resulting in a new array `[2, 4, 6, 8, 10]`.

Added in v2.0.0

copy

Copies an array.

Signature

export declare const copy: { <A>(self: readonly [A, ...A[]]): [A, ...A[]]; <A>(self: readonly A[]): A[] }

Example

import { Array } from "effect"

const numbers = [1, 2, 3]
const copy = Array.copy(numbers)
assert.deepStrictEqual(copy, [1, 2, 3])

Added in v2.0.0

dedupe

Remove duplicates from an Iterable, preserving the order of the first occurrence of each element. The equivalence used to compare elements is provided by Equal.equivalence() from the Equal module.

Signature

export declare const dedupe: <S extends readonly [any, ...any[]] | Iterable<any>>(
  self: S
) => S extends readonly [infer A, ...(infer A)[]] ? [A, ...A[]] : S extends Iterable<infer A> ? A[] : never

Added in v2.0.0

dedupeAdjacent

Deduplicates adjacent elements that are identical.

Signature

export declare const dedupeAdjacent: <A>(self: Iterable<A>) => A[]

Example

import { Array } from "effect"

const numbers = [1, 1, 2, 2, 3, 3]
const unique = Array.dedupeAdjacent(numbers)
assert.deepStrictEqual(unique, [1, 2, 3])

Added in v2.0.0

dedupeAdjacentWith

Deduplicates adjacent elements that are identical using the provided isEquivalent function.

Signature

export declare const dedupeAdjacentWith: {
  <A>(isEquivalent: (self: A, that: A) => boolean): (self: Iterable<A>) => A[]
  <A>(self: Iterable<A>, isEquivalent: (self: A, that: A) => boolean): A[]
}

Example

import { Array } from "effect"

const numbers = [1, 1, 2, 2, 3, 3]
const unique = Array.dedupeAdjacentWith(numbers, (a, b) => a === b)
assert.deepStrictEqual(unique, [1, 2, 3])

Added in v2.0.0

dedupeWith

Remove duplicates from an Iterable using the provided isEquivalent function, preserving the order of the first occurrence of each element.

Signature

export declare const dedupeWith: {
  <S extends Iterable<any>>(
    isEquivalent: (self: ReadonlyArray.Infer<S>, that: ReadonlyArray.Infer<S>) => boolean
  ): (self: S) => ReadonlyArray.With<S, ReadonlyArray.Infer<S>>
  <A>(self: readonly [A, ...A[]], isEquivalent: (self: A, that: A) => boolean): [A, ...A[]]
  <A>(self: Iterable<A>, isEquivalent: (self: A, that: A) => boolean): A[]
}

Example

import { Array } from "effect"

const numbers = [1, 2, 2, 3, 3, 3]
const unique = Array.dedupeWith(numbers, (a, b) => a === b)
assert.deepStrictEqual(unique, [1, 2, 3])

Added in v2.0.0

difference

Creates a Array of values not included in the other given Iterable. The order and references of result values are determined by the first Iterable.

Signature

export declare const difference: {
  <A>(that: Iterable<A>): (self: Iterable<A>) => A[]
  <A>(self: Iterable<A>, that: Iterable<A>): A[]
}

Example

import { Array } from "effect"

const array1 = [1, 2, 3]
const array2 = [2, 3, 4]
const difference = Array.difference(array1, array2)
assert.deepStrictEqual(difference, [1])

Added in v2.0.0

differenceWith

Creates a Array of values not included in the other given Iterable using the provided isEquivalent function. The order and references of result values are determined by the first Iterable.

Signature

export declare const differenceWith: <A>(isEquivalent: (self: A, that: A) => boolean) => {
  (that: Iterable<A>): (self: Iterable<A>) => A[]
  (self: Iterable<A>, that: Iterable<A>): A[]
}

Example

import { Array } from "effect"

const array1 = [1, 2, 3]
const array2 = [2, 3, 4]
const difference = Array.differenceWith<number>((a, b) => a === b)(array1, array2)
assert.deepStrictEqual(difference, [1])

Added in v2.0.0

extend

Extends an array with a function that maps each subarray to a value.

Signature

export declare const extend: {
  <A, B>(f: (as: readonly A[]) => B): (self: readonly A[]) => B[]
  <A, B>(self: readonly A[], f: (as: readonly A[]) => B): B[]
}

Example

import { Array } from "effect"

const numbers = [1, 2, 3]
const result = Array.extend(numbers, (as) => as.length)
assert.deepStrictEqual(result, [3, 2, 1])

// Explanation:
// The function maps each subarray starting from each element to its length.
// The subarrays are: [1, 2, 3], [2, 3], [3].
// The lengths are: 3, 2, 1.
// Therefore, the result is [3, 2, 1].

Added in v2.0.0

forEach

Performs a side-effect for each element of the Iterable.

Signature

export declare const forEach: {
  <A>(f: (a: A, i: number) => void): (self: Iterable<A>) => void
  <A>(self: Iterable<A>, f: (a: A, i: number) => void): void
}

Example

import { Array } from "effect"

const numbers = [1, 2, 3]
Array.forEach(numbers, (n) => console.log(n)) // 1, 2, 3

Added in v2.0.0

insertAt

Insert an element at the specified index, creating a new NonEmptyArray, or return None if the index is out of bounds.

Signature

export declare const insertAt: {
  <B>(i: number, b: B): <A>(self: Iterable<A>) => Option<[B | A, ...(B | A)[]]>
  <A, B>(self: Iterable<A>, i: number, b: B): Option<[A | B, ...(A | B)[]]>
}

Example

import { Array, Option } from "effect"

const letters = ["a", "b", "c", "e"]
const result = Array.insertAt(letters, 3, "d")
assert.deepStrictEqual(result, Option.some(["a", "b", "c", "d", "e"]))

Added in v2.0.0

intersection

Creates an Array of unique values that are included in all given Iterables. The order and references of result values are determined by the first Iterable.

Signature

export declare const intersection: {
  <B>(that: Iterable<B>): <A>(self: Iterable<A>) => (A & B)[]
  <A, B>(self: Iterable<A>, that: Iterable<B>): (A & B)[]
}

Example

import { Array } from "effect"

const array1 = [1, 2, 3]
const array2 = [3, 4, 1]
const result = Array.intersection(array1, array2)
assert.deepStrictEqual(result, [1, 3])

Added in v2.0.0

intersectionWith

Creates an Array of unique values that are included in all given Iterables using the provided isEquivalent function. The order and references of result values are determined by the first Iterable.

Signature

export declare const intersectionWith: <A>(isEquivalent: (self: A, that: A) => boolean) => {
  (that: Iterable<A>): (self: Iterable<A>) => A[]
  (self: Iterable<A>, that: Iterable<A>): A[]
}

Example

import { Array } from "effect"

const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }]
const array2 = [{ id: 3 }, { id: 4 }, { id: 1 }]
const isEquivalent = (a: { id: number }, b: { id: number }) => a.id === b.id
const result = Array.intersectionWith(isEquivalent)(array2)(array1)
assert.deepStrictEqual(result, [{ id: 1 }, { id: 3 }])

Added in v2.0.0

intersperse

Places an element in between members of an Iterable. If the input is a non-empty array, the result is also a non-empty array.

Signature

export declare const intersperse: {
  <B>(middle: B): <S extends Iterable<any>>(self: S) => ReadonlyArray.With<S, B | ReadonlyArray.Infer<S>>
  <A, B>(self: readonly [A, ...A[]], middle: B): [A | B, ...(A | B)[]]
  <A, B>(self: Iterable<A>, middle: B): (A | B)[]
}

Example

import { Array } from "effect"

const numbers = [1, 2, 3]
const result = Array.intersperse(numbers, 0)
assert.deepStrictEqual(result, [1, 0, 2, 0, 3])

Added in v2.0.0

max

Finds the maximum element in an array based on a comparator.

Signature

export declare const max: {
  <A>(O: Order.Order<A>): (self: readonly [A, ...A[]]) => A
  <A>(self: readonly [A, ...A[]], O: Order.Order<A>): A
}

Example

import { Array, Order } from "effect"

const max = Array.max([3, 1, 2], Order.number)
assert.deepStrictEqual(max, 3)

Added in v2.0.0

min

Finds the minimum element in an array based on a comparator.

Signature

export declare const min: {
  <A>(O: Order.Order<A>): (self: readonly [A, ...A[]]) => A
  <A>(self: readonly [A, ...A[]], O: Order.Order<A>): A
}

Example

import { Array, Order } from "effect"

const min = Array.min([3, 1, 2], Order.number)
assert.deepStrictEqual(min, 1)

Added in v2.0.0

modify

Apply a function to the element at the specified index, creating a new Array, or return a copy of the input if the index is out of bounds.

Signature

export declare const modify: {
  <A, B>(i: number, f: (a: A) => B): (self: Iterable<A>) => (A | B)[]
  <A, B>(self: Iterable<A>, i: number, f: (a: A) => B): (A | B)[]
}

Example

import { Array } from "effect"

const numbers = [1, 2, 3, 4]
const result = Array.modify(numbers, 2, (n) => n * 2)
assert.deepStrictEqual(result, [1, 2, 6, 4])

Added in v2.0.0

modifyNonEmptyHead

Apply a function to the head, creating a new NonEmptyReadonlyArray.

Signature

export declare const modifyNonEmptyHead: {
  <A, B>(f: (a: A) => B): (self: readonly [A, ...A[]]) => [A | B, ...(A | B)[]]
  <A, B>(self: readonly [A, ...A[]], f: (a: A) => B): [A | B, ...(A | B)[]]
}

Example

import { Array } from "effect"

const result = Array.modifyNonEmptyHead([1, 2, 3], (n) => n * 10)
assert.deepStrictEqual(result, [10, 2, 3])

Added in v2.0.0

modifyNonEmptyLast

Apply a function to the last element, creating a new NonEmptyReadonlyArray.

Signature

export declare const modifyNonEmptyLast: {
  <A, B>(f: (a: A) => B): (self: readonly [A, ...A[]]) => [A | B, ...(A | B)[]]
  <A, B>(self: readonly [A, ...A[]], f: (a: A) => B): [A | B, ...(A | B)[]]
}

Example

import { Array } from "effect"

const result = Array.modifyNonEmptyLast([1, 2, 3], (n) => n * 2)
assert.deepStrictEqual(result, [1, 2, 6])

Added in v2.0.0

modifyOption

Apply a function to the element at the specified index, creating a new Array, or return None if the index is out of bounds.

Signature

export declare const modifyOption: {
  <A, B>(i: number, f: (a: A) => B): (self: Iterable<A>) => Option<(A | B)[]>
  <A, B>(self: Iterable<A>, i: number, f: (a: A) => B): Option<(A | B)[]>
}

Example

import { Array, Option } from "effect"

const numbers = [1, 2, 3, 4]
const result = Array.modifyOption(numbers, 2, (n) => n * 2)
assert.deepStrictEqual(result, Option.some([1, 2, 6, 4]))

const outOfBoundsResult = Array.modifyOption(numbers, 5, (n) => n * 2)
assert.deepStrictEqual(outOfBoundsResult, Option.none())

Added in v2.0.0

remove

Delete the element at the specified index, creating a new Array, or return a copy of the input if the index is out of bounds.

Signature

export declare const remove: { (i: number): <A>(self: Iterable<A>) => A[]; <A>(self: Iterable<A>, i: number): A[] }

Example

import { Array } from "effect"

const numbers = [1, 2, 3, 4]
const result = Array.remove(numbers, 2)
assert.deepStrictEqual(result, [1, 2, 4])

const outOfBoundsResult = Array.remove(numbers, 5)
assert.deepStrictEqual(outOfBoundsResult, [1, 2, 3, 4])

Added in v2.0.0

replace

Change the element at the specified index, creating a new Array, or return a copy of the input if the index is out of bounds.

Signature

export declare const replace: {
  <B>(i: number, b: B): <A>(self: Iterable<A>) => (B | A)[]
  <A, B>(self: Iterable<A>, i: number, b: B): (A | B)[]
}

Example

import { Array } from "effect"

const letters = ["a", "b", "c", "d"]
const result = Array.replace(1, "z")(letters)
assert.deepStrictEqual(result, ["a", "z", "c", "d"])

Added in v2.0.0

replaceOption

Replaces an element in an array with the given value, returning an option of the updated array.

Signature

export declare const replaceOption: {
  <B>(i: number, b: B): <A>(self: Iterable<A>) => Option<(B | A)[]>
  <A, B>(self: Iterable<A>, i: number, b: B): Option<(A | B)[]>
}

Example

import { Array, Option } from "effect"

const numbers = [1, 2, 3]
const result = Array.replaceOption(numbers, 1, 4)
assert.deepStrictEqual(result, Option.some([1, 4, 3]))

Added in v2.0.0

rotate

Rotate an Iterable by n steps. If the input is a non-empty array, the result is also a non-empty array.

Signature

export declare const rotate: {
  (n: number): <S extends Iterable<any>>(self: S) => ReadonlyArray.With<S, ReadonlyArray.Infer<S>>
  <A>(self: readonly [A, ...A[]], n: number): [A, ...A[]]
  <A>(self: Iterable<A>, n: number): A[]
}

Example

import { Array } from "effect"

const letters = ["a", "b", "c", "d"]
const result = Array.rotate(letters, 2)
assert.deepStrictEqual(result, ["c", "d", "a", "b"])

Added in v2.0.0

setNonEmptyHead

Change the head, creating a new NonEmptyReadonlyArray.

Signature

export declare const setNonEmptyHead: {
  <B>(b: B): <A>(self: readonly [A, ...A[]]) => [B | A, ...(B | A)[]]
  <A, B>(self: readonly [A, ...A[]], b: B): [A | B, ...(A | B)[]]
}

Example

import { Array } from "effect"

const result = Array.setNonEmptyHead([1, 2, 3], 10)
assert.deepStrictEqual(result, [10, 2, 3])

Added in v2.0.0

setNonEmptyLast

Change the last element, creating a new NonEmptyReadonlyArray.

Signature

export declare const setNonEmptyLast: {
  <B>(b: B): <A>(self: readonly [A, ...A[]]) => [B | A, ...(B | A)[]]
  <A, B>(self: readonly [A, ...A[]], b: B): [A | B, ...(A | B)[]]
}

Example

import { Array } from "effect"

const result = Array.setNonEmptyLast([1, 2, 3], 4)
assert.deepStrictEqual(result, [1, 2, 4])

Added in v2.0.0

union

Creates a union of two arrays, removing duplicates.

Signature

export declare const union: {
  <T extends Iterable<any>>(
    that: T
  ): <S extends Iterable<any>>(
    self: S
  ) => ReadonlyArray.OrNonEmpty<S, T, ReadonlyArray.Infer<S> | ReadonlyArray.Infer<T>>
  <A, B>(self: readonly [A, ...A[]], that: readonly B[]): [A | B, ...(A | B)[]]
  <A, B>(self: readonly A[], that: readonly [B, ...B[]]): [A | B, ...(A | B)[]]
  <A, B>(self: Iterable<A>, that: Iterable<B>): (A | B)[]
}

Example

import { Array } from "effect"

const array1 = [1, 2]
const array2 = [2, 3]
const result = Array.union(array1, array2)
assert.deepStrictEqual(result, [1, 2, 3])

Added in v2.0.0

unionWith

Calculates the union of two arrays using the provided equivalence relation.

Signature

export declare const unionWith: {
  <S extends Iterable<any>, T extends Iterable<any>>(
    that: T,
    isEquivalent: (self: ReadonlyArray.Infer<S>, that: ReadonlyArray.Infer<T>) => boolean
  ): (self: S) => ReadonlyArray.OrNonEmpty<S, T, ReadonlyArray.Infer<S> | ReadonlyArray.Infer<T>>
  <A, B>(
    self: readonly [A, ...A[]],
    that: Iterable<B>,
    isEquivalent: (self: A, that: B) => boolean
  ): [A | B, ...(A | B)[]]
  <A, B>(
    self: Iterable<A>,
    that: readonly [B, ...B[]],
    isEquivalent: (self: A, that: B) => boolean
  ): [A | B, ...(A | B)[]]
  <A, B>(self: Iterable<A>, that: Iterable<B>, isEquivalent: (self: A, that: B) => boolean): (A | B)[]
}

Example

import { Array } from "effect"

const array1 = [1, 2]
const array2 = [2, 3]
const union = Array.unionWith(array1, array2, (a, b) => a === b)
assert.deepStrictEqual(union, [1, 2, 3])

Added in v2.0.0

unzip

This function is the inverse of zip. Takes an Iterable of pairs and return two corresponding Arrays.

Signature

export declare const unzip: <
  S extends Iterable<readonly [any, any]> | readonly [readonly [any, any], ...(readonly [any, any])[]]
>(
  self: S
) => S extends readonly [readonly [infer A, infer B], ...(readonly [infer A, infer B])[]]
  ? [[A, ...A[]], [B, ...B[]]]
  : S extends Iterable<readonly [infer A, infer B]>
    ? [A[], B[]]
    : never

Example

import { Array } from "effect"

const result = Array.unzip([
  [1, "a"],
  [2, "b"],
  [3, "c"]
])
assert.deepStrictEqual(result, [
  [1, 2, 3],
  ["a", "b", "c"]
])

Added in v2.0.0

zipping

zip

Takes two Iterables and returns an Array of corresponding pairs. If one input Iterable is short, excess elements of the longer Iterable are discarded.

Signature

export declare const zip: {
  <B>(that: readonly [B, ...B[]]): <A>(self: readonly [A, ...A[]]) => [[A, B], ...[A, B][]]
  <B>(that: Iterable<B>): <A>(self: Iterable<A>) => [A, B][]
  <A, B>(self: readonly [A, ...A[]], that: readonly [B, ...B[]]): [[A, B], ...[A, B][]]
  <A, B>(self: Iterable<A>, that: Iterable<B>): [A, B][]
}

Example

import { Array } from "effect"

const array1 = [1, 2, 3]
const array2 = ["a", "b"]
const result = Array.zip(array1, array2)
assert.deepStrictEqual(result, [
  [1, "a"],
  [2, "b"]
])

Added in v2.0.0

zipWith

Apply a function to pairs of elements at the same index in two Iterables, collecting the results in a new Array. If one input Iterable is short, excess elements of the longer Iterable are discarded.

Signature

export declare const zipWith: {
  <B, A, C>(that: readonly [B, ...B[]], f: (a: A, b: B) => C): (self: readonly [A, ...A[]]) => [C, ...C[]]
  <B, A, C>(that: Iterable<B>, f: (a: A, b: B) => C): (self: Iterable<A>) => C[]
  <A, B, C>(self: readonly [A, ...A[]], that: readonly [B, ...B[]], f: (a: A, b: B) => C): [C, ...C[]]
  <B, A, C>(self: Iterable<A>, that: Iterable<B>, f: (a: A, b: B) => C): C[]
}

Example

import { Array } from "effect"

const array1 = [1, 2, 3]
const array2 = [4, 5, 6]
const result = Array.zipWith(array1, array2, (a, b) => a + b)
assert.deepStrictEqual(result, [5, 7, 9])

Added in v2.0.0