Skip to content

Array

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

136 exports Added in v2.0.0 Source

Concatenating

append

Added in v2.0.0 Source

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

Signature

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

Example

import { Array } from "effect"

const result = Array.append([1, 2, 3], 4)
console.log(result) // [1, 2, 3, 4]

appendAll

Added in v2.0.0 Source

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

Signature

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

prepend

Added in v2.0.0 Source

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

Signature

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

Example

import { Array } from "effect"

const result = Array.prepend([2, 3, 4], 1)
console.log(result) // [1, 2, 3, 4]

prependAll

Added in v2.0.0 Source

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

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

Example

import { Array } from "effect"

const result = Array.prependAll([2, 3], [0, 1])
console.log(result) // [0, 1, 2, 3]

Constructors

allocate

Added in v2.0.0 Source

Creates a new Array of the specified length.

Signature

declare function allocate<A = never>(n: number): Array<A | undefined>;

empty

Added in v2.0.0 Source

Signature

declare const empty: <A = never>() => Array<A>;

ensure

Added in v3.3.0 Source

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

Signature

declare function ensure<A>(self: A | readonly Array<A>): Array<A>

fromIterable

Added in v2.0.0 Source

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

declare function fromIterable<A>(collection: Iterable<A>): Array<A>;

make

Added in v2.0.0 Source

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

Signature

declare function make<Elements extends [any, ...Array<any>]>(
  ...elements: Elements
): [Elements[number], ...Array<Elements[number]>];

makeBy

Added in v2.0.0 Source

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

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

Signature

declare const makeBy: {
  <A>(f: (i: number) => A): (n: number) => [A, ...Array<A>];
  <A>(n: number, f: (i: number) => A): [A, ...Array<A>];
};

Example

import { makeBy } from "effect/Array"

const result = makeBy(5, (n) => n * 2)
console.log(result) // [0, 2, 4, 6, 8]

of

Added in v2.0.0 Source

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

Signature

declare function of<A>(a: A): [A, ...Array<A>];

range

Added in v2.0.0 Source

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

Signature

declare function range(start: number, end: number): [number, ...Array<number>];

replicate

Added in v2.0.0 Source

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

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

Signature

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

Example

import { Array } from "effect"

const result = Array.replicate("a", 3)
console.log(result) // ["a", "a", "a"]

unfold

Added in v2.0.0 Source

Signature

declare function unfold<B, A>(b: B, f: (b: B) => Option<readonly [A, B]>): Array<A>;

Conversions

fromNullable

Added in v2.0.0 Source

Signature

declare function fromNullable<A>(a: A): Array<NonNullable<A>>;

fromOption

Added in v2.0.0 Source

Converts an Option to an array.

Signature

declare const fromOption: <A>(self: Option.Option<A>) => Array<A>;

Example

import { Array, Option } from "effect"

console.log(Array.fromOption(Option.some(1))) // [1]
console.log(Array.fromOption(Option.none())) // []

fromRecord

Added in v2.0.0 Source

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

Signature

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

Example

import { Array } from "effect"

const result = Array.fromRecord({ a: 1, b: 2, c: 3 })
console.log(result) // [["a", 1], ["b", 2], ["c", 3]]

Do Notation

bind

Added in v3.2.0 Source

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 Array 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

See

Signature

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

Example

import { Array, pipe } from "effect"

const doResult = pipe(
  Array.Do,
  Array.bind("x", () => [1, 3, 5]),
  Array.bind("y", () => [2, 4, 6]),
  Array.filter(({ x, y }) => x < y), // condition
  Array.map(({ x, y }) => [x, y] as const), // transformation
)
console.log(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)
  }
}

bindTo

Added in v3.2.0 Source

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 Array 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

See

Signature

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

Example

import { Array, pipe } from "effect"

const doResult = pipe(
  Array.Do,
  Array.bind("x", () => [1, 3, 5]),
  Array.bind("y", () => [2, 4, 6]),
  Array.filter(({ x, y }) => x < y), // condition
  Array.map(({ x, y }) => [x, y] as const), // transformation
)
console.log(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)
  }
}

Do

Added in v3.2.0 Source

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 Array 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

See

Signature

declare const Do: ReadonlyArray<{}>;

Example

import { Array, pipe } from "effect"

const doResult = pipe(
  Array.Do,
  Array.bind("x", () => [1, 3, 5]),
  Array.bind("y", () => [2, 4, 6]),
  Array.filter(({ x, y }) => x < y), // condition
  Array.map(({ x, y }) => [x, y] as const), // transformation
)
console.log(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)
  }
}

Elements

cartesian

Added in v2.0.0 Source

Zips this chunk crosswise with the specified chunk.

Signature

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

Example

import { Array } from "effect"

const result = Array.cartesian([1, 2], ["a", "b"])
console.log(result) // [[1, "a"], [1, "b"], [2, "a"], [2, "b"]]

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

Signature

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

Example

import { Array } from "effect"

const result = Array.cartesianWith([1, 2], ["a", "b"], (a, b) => `${a}-${b}`)
console.log(result) // ["1-a", "1-b", "2-a", "2-b"]

contains

Added in v2.0.0 Source

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

Signature

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

Example

import { Array, pipe } from "effect"

const result = pipe(["a", "b", "c", "d"], Array.contains("c"))
console.log(result) // true

containsWith

Added in v2.0.0 Source

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

Signature

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

every

Added in v2.0.0 Source

Check if a predicate holds true for every ReadonlyArray element.

Signature

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

findFirst

Added in v2.0.0 Source

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

Signature

declare const findFirst: {
  <A, B>(f: (a: NoInfer<A>, i: number) => Option<B>): (self: Iterable<A>) => Option<B>;
  <A, B>(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>(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 } from "effect"

const result = Array.findFirst([1, 2, 3, 4, 5], (x) => x > 3)
console.log(result) // Option.some(4)

Return the first index for which a predicate holds.

Signature

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 } from "effect"

const result = Array.findFirstIndex([5, 3, 8, 9], (x) => x > 5)
console.log(result) // Option.some(2)

Returns a tuple of the first element that satisfies the specified predicate and its index, or None if no such element exists.

Signature

declare const findFirstWithIndex: {
  <A, B>(f: (a: NoInfer<A>, i: number) => Option<B>): (self: Iterable<A>) => Option<[B, number]>;
  <A, B>(
    refinement: (a: NoInfer<A>, i: number) => a is B,
  ): (self: Iterable<A>) => Option<[B, number]>;
  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => Option<[A, number]>;
  <A, B>(self: Iterable<A>, f: (a: A, i: number) => Option<B>): Option<[B, number]>;
  <A, B>(self: Iterable<A>, refinement: (a: A, i: number) => a is B): Option<[B, number]>;
  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Option<[A, number]>;
};

Example

import { Array } from "effect"

const result = Array.findFirstWithIndex([1, 2, 3, 4, 5], (x) => x > 3)
console.log(result) // Option.some([4, 3])

findLast

Added in v2.0.0 Source

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

declare const findLast: {
  <A, B>(f: (a: NoInfer<A>, i: number) => Option<B>): (self: Iterable<A>) => Option<B>;
  <A, B>(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>(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 } from "effect"

const result = Array.findLast([1, 2, 3, 4, 5], (n) => n % 2 === 0)
console.log(result) // Option.some(4)

Return the last index for which a predicate holds.

Signature

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 } from "effect"

const result = Array.findLastIndex([1, 3, 8, 9], (x) => x < 5)
console.log(result) // Option.some(1)

reverse

Added in v2.0.0 Source

Reverse an Iterable, creating a new Array.

Signature

declare function reverse<S extends Iterable<any, any, any>>(
  self: S,
): S extends readonly [A, A]
  ? [A, ...Array<A>]
  : S extends Iterable<A, any, any>
    ? Array<A>
    : never;

some

Added in v2.0.0 Source

Check if a predicate holds true for some ReadonlyArray element.

Signature

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

sortWith

Added in v2.0.0 Source

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

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

Example

import { Array, Order } from "effect"

const result = Array.sortWith(["aaa", "b", "cc"], (s) => s.length, Order.number)
console.log(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.

Filtering

filter

Added in v2.0.0 Source

Signature

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

filterMap

Added in v2.0.0 Source

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

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

Example

import { Array, Option } from "effect"

const evenSquares = (x: number) => (x % 2 === 0 ? Option.some(x * x) : Option.none())

const result = Array.filterMap([1, 2, 3, 4, 5], evenSquares)
console.log(result) // [4, 16]

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

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

Example

import { Array, Option } from "effect"

const toSquareTillOdd = (x: number) => (x % 2 === 0 ? Option.some(x * x) : Option.none())

const result = Array.filterMapWhile([2, 4, 5], toSquareTillOdd)
console.log(result) // [4, 16]

getLefts

Added in v2.0.0 Source

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

Signature

declare function getLefts<T extends Iterable<Either<any, any>, any, any>>(
  self: T,
): Array<Left<Infer<T>>>;

getRights

Added in v2.0.0 Source

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

Signature

declare function getRights<T extends Iterable<Either<any, any>, any, any>>(
  self: T,
): Array<Right<Infer<T>>>;

getSomes

Added in v2.0.0 Source

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

Signature

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

Example

import { Array, Option } from "effect"

const result = Array.getSomes([Option.some(1), Option.none(), Option.some(2)])
console.log(result) // [1, 2]

partition

Added in v2.0.0 Source

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

Signature

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

Example

import { Array } from "effect"

const result = Array.partition([1, 2, 3, 4], (n) => n % 2 === 0)
console.log(result) // [[1, 3], [2, 4]]

partitionMap

Added in v2.0.0 Source

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

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

Example

import { Array, Either } from "effect"

const isEven = (x: number) => x % 2 === 0

const result = Array.partitionMap([1, 2, 3, 4, 5], (x) =>
  isEven(x) ? Either.right(x) : Either.left(x),
)
console.log(result)
// [
//   [1, 3, 5],
//   [2, 4]
// ]

separate

Added in v2.0.0 Source

Separates an Iterable into two arrays based on a predicate.

Signature

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

Folding

countBy

Added in v3.16.0 Source

Counts all the element of the given array that pass the given predicate

Signature

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

Example

import { Array } from "effect"

const result = Array.countBy([1, 2, 3, 4, 5], (n) => n % 2 === 0)
console.log(result) // 2

join

Added in v2.0.0 Source

Joins the elements together with "sep" in the middle.

Signature

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, "-")
console.log(joined) // "a-b-c"

mapAccum

Added in v2.0.0 Source

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

Signature

declare const mapAccum: {
  <S, A, B, I extends Iterable<A, any, any> = Iterable<A, any, any>>(
    s: S,
    f: (s: S, a: Infer<I>, i: number) => readonly [S, B],
  ): (self: I) => [state: S, mappedArray: With<I, B>];
  <S, A, B, I extends Iterable<A, any, any> = Iterable<A, any, any>>(
    self: I,
    s: S,
    f: (s: S, a: Infer<I>, i: number) => readonly [S, B],
  ): [state: S, mappedArray: With<I, B>];
};

Example

import { Array } from "effect"

const result = Array.mapAccum([1, 2, 3], 0, (acc, n) => [acc + n, acc + n])
console.log(result) // [6, [1, 3, 6]]

reduce

Added in v2.0.0 Source

Reduces an array from the left.

Signature

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 result = Array.reduce([1, 2, 3], 0, (acc, n) => acc + n)
console.log(result) // 6

reduceRight

Added in v2.0.0 Source

Reduces an array from the right.

Signature

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 result = Array.reduceRight([1, 2, 3], 0, (acc, n) => acc + n)
console.log(result) // 6

scan

Added in v2.0.0 Source

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

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

Example

import { Array } from "effect"

const result = Array.scan([1, 2, 3, 4], 0, (acc, value) => acc + value)
console.log(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.

scanRight

Added in v2.0.0 Source

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

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

Example

import { Array } from "effect"

const result = Array.scanRight([1, 2, 3, 4], 0, (acc, value) => acc + value)
console.log(result) // [10, 9, 7, 4, 0]

Getters

drop

Added in v2.0.0 Source

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

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

Example

import { Array } from "effect"

const result = Array.drop([1, 2, 3, 4, 5], 2)
console.log(result) // [3, 4, 5]

dropRight

Added in v2.0.0 Source

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

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

Example

import { Array } from "effect"

const result = Array.dropRight([1, 2, 3, 4, 5], 2)
console.log(result) // [1, 2, 3]

dropWhile

Added in v2.0.0 Source

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

Signature

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

Example

import { Array } from "effect"

const result = Array.dropWhile([1, 2, 3, 4, 5], (x) => x < 4)
console.log(result) // [4, 5]

get

Added in v2.0.0 Source

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

Signature

declare const get: {
  (index: number): <A>(self: readonly Array<A>) => Option<A>;
  <A>(self: readonly Array<A>, index: number): Option<A>;
}

headNonEmpty

Added in v2.0.0 Source

Get the first element of a non empty array.

Signature

declare const headNonEmpty: <A>(self: NonEmptyReadonlyArray<A>) => A;

Example

import { Array } from "effect"

const result = Array.headNonEmpty([1, 2, 3, 4])
console.log(result) // 1

init

Added in v2.0.0 Source

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

Signature

declare function init<A>(self: Iterable<A>): Option<Array<A>>;

initNonEmpty

Added in v2.0.0 Source

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

Signature

declare function initNonEmpty<A>(self: readonly [A, A]): Array<A>;

last

Added in v2.0.0 Source

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

Signature

declare function last<A>(self: readonly Array<A>): Option<A>

lastNonEmpty

Added in v2.0.0 Source

Get the last element of a non empty array.

Signature

declare function lastNonEmpty<A>(self: readonly [A, A]): A;

length

Added in v2.0.0 Source

Return the number of elements in a ReadonlyArray.

Signature

declare function length<A>(self: readonly Array<A>): number

tail

Added in v2.0.0 Source

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

Signature

declare function tail<A>(self: Iterable<A>): Option<Array<A>>;

tailNonEmpty

Added in v2.0.0 Source

Get all but the first element of a NonEmptyReadonlyArray.

Signature

declare function tailNonEmpty<A>(self: readonly [A, A]): Array<A>;

take

Added in v2.0.0 Source

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

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

Example

import { Array } from "effect"

const result = Array.take([1, 2, 3, 4, 5], 3)
console.log(result) // [1, 2, 3]

takeRight

Added in v2.0.0 Source

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

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

Example

import { Array } from "effect"

const result = Array.takeRight([1, 2, 3, 4, 5], 3)
console.log(result) // [3, 4, 5]

takeWhile

Added in v2.0.0 Source

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

Signature

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

Example

import { Array } from "effect"

const result = Array.takeWhile([1, 3, 2, 4, 1, 2], (x) => x < 4)
console.log(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.

Grouping

group

Added in v2.0.0 Source

Group equal, consecutive elements of a NonEmptyReadonlyArray into NonEmptyArrays.

Signature

declare const group: <A>(self: NonEmptyReadonlyArray<A>) => NonEmptyArray<NonEmptyArray<A>>;

Example

import { Array } from "effect"

const result = Array.group([1, 1, 2, 2, 2, 3, 1])
console.log(result) // [[1, 1], [2, 2, 2], [3], [1]]

groupBy

Added in v2.0.0 Source

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

declare const groupBy: {
  <A, K extends string | symbol>(
    f: (a: A) => K,
  ): (self: Iterable<A>) => Record<Record.ReadonlyRecord.NonLiteralKey<K>, NonEmptyArray<A>>;
  <A, K extends string | symbol>(
    self: Iterable<A>,
    f: (a: A) => K,
  ): Record<Record.ReadonlyRecord.NonLiteralKey<K>, NonEmptyArray<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)
console.log(result)
// {
//  A: [{ name: "Alice", group: "A" }, { name: "Charlie", group: "A" }],
//  B: [{ name: "Bob", group: "B" }]
// }

groupWith

Added in v2.0.0 Source

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

Signature

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

Example

import { Array } from "effect"

const result = Array.groupWith(["a", "a", "b", "b", "b", "c", "a"], (x, y) => x === y)
console.log(result) // [["a", "a"], ["b", "b", "b"], ["c"], ["a"]]

Guards

isArray

Added in v2.0.0 Source

Determine if unknown is an Array.

Signature

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

Example

import { Array } from "effect"

console.log(Array.isArray(null)) // false
console.log(Array.isArray([1, 2, 3])) // true

isEmptyArray

Added in v2.0.0 Source

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

Signature

declare function isEmptyArray<A>(self: Array<A>): self is [];

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

Signature

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

Example

import { Array } from "effect"

console.log(Array.isEmptyReadonlyArray([])) // true
console.log(Array.isEmptyReadonlyArray([1, 2, 3])) // false

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

declare const isNonEmptyArray: <A>(self: Array<A>) => self is NonEmptyArray<A>;

Example

import { Array } from "effect"

console.log(Array.isNonEmptyArray([])) // false
console.log(Array.isNonEmptyArray([1, 2, 3])) // true

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

declare const isNonEmptyReadonlyArray: <A>(
  self: ReadonlyArray<A>,
) => self is NonEmptyReadonlyArray<A>;

Example

import { Array } from "effect"

console.log(Array.isNonEmptyReadonlyArray([])) // false
console.log(Array.isNonEmptyReadonlyArray([1, 2, 3])) // true

Instances

Creates an equivalence relation for arrays.

Signature

declare const getEquivalence: <A>(
  isEquivalent: Equivalence.Equivalence<A>,
) => Equivalence.Equivalence<ReadonlyArray<A>>;

Example

import { Array } from "effect"

const eq = Array.getEquivalence<number>((a, b) => a === b)
console.log(eq([1, 2, 3], [1, 2, 3])) // true

getOrder

Added in v2.0.0 Source

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

declare const getOrder: <A>(O: Order.Order<A>) => Order.Order<ReadonlyArray<A>>;

Lifting

liftEither

Added in v2.0.0 Source

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

declare function liftEither<A extends Array<unknown>, E, B>(
  f: (...a: A) => Either<B, E>,
): (...a: A) => Array<B>;

liftNullable

Added in v2.0.0 Source

Signature

declare function liftNullable<A extends Array<unknown>, B>(
  f: (...a: A) => B | null | undefined,
): (...a: A) => Array<NonNullable<B>>;

liftOption

Added in v2.0.0 Source

Signature

declare function liftOption<A extends Array<unknown>, B>(
  f: (...a: A) => Option<B>,
): (...a: A) => Array<B>;

Lifts a predicate into an array.

Signature

declare const liftPredicate: {
  <A, B>(refinement: Refinement<A, B>): (a: A) => Array<B>;
  <A>(predicate: Predicate<A>): <B>(b: B) => Array<B>;
};

Example

import { Array } from "effect"

const isEven = (n: number) => n % 2 === 0
const to = Array.liftPredicate(isEven)
console.log(to(1)) // []
console.log(to(2)) // [2]

Mapping

map

Added in v2.0.0 Source

Signature

declare const map: {
  <S extends readonly Array<any>, B>(f: (a: Infer<S>, i: number) => B): (self: S) => With<S, B>;
  <S extends readonly Array<any>, B>(self: S, f: (a: Infer<S>, i: number) => B): With<S, B>;
}

Models

NonEmptyArray type

Added in v2.0.0 Source

Signature

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

Signature

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

Other

chop

Added in v2.0.0 Source

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

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

Example

import { Array } from "effect"

const result = Array.chop([1, 2, 3, 4, 5], (as): [number, Array<number>] => [
  as[0] * 2,
  as.slice(1),
])
console.log(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]`.

copy

Added in v2.0.0 Source

Copies an array.

Signature

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

Example

import { Array } from "effect"

const result = Array.copy([1, 2, 3])
console.log(result) // [1, 2, 3]

dedupe

Added in v2.0.0 Source

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

declare function dedupe<S extends Iterable<any, any, any>>(
  self: S,
): S extends readonly [A, A]
  ? [A, ...Array<A>]
  : S extends Iterable<A, any, any>
    ? Array<A>
    : never;

Deduplicates adjacent elements that are identical.

Signature

declare const dedupeAdjacent: <A>(self: Iterable<A>) => Array<A>;

Example

import { Array } from "effect"

const result = Array.dedupeAdjacent([1, 1, 2, 2, 3, 3])
console.log(result) // [1, 2, 3]

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

Signature

declare const dedupeAdjacentWith: {
  <A>(isEquivalent: (self: A, that: A) => boolean): (self: Iterable<A>) => Array<A>;
  <A>(self: Iterable<A>, isEquivalent: (self: A, that: A) => boolean): Array<A>;
};

Example

import { Array } from "effect"

const result = Array.dedupeAdjacentWith([1, 1, 2, 2, 3, 3], (a, b) => a === b)
console.log(result) // [1, 2, 3]

dedupeWith

Added in v2.0.0 Source

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

Signature

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

Example

import { Array } from "effect"

const result = Array.dedupeWith([1, 2, 2, 3, 3, 3], (a, b) => a === b)
console.log(result) // [1, 2, 3]

difference

Added in v2.0.0 Source

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

declare const difference: {
  <A>(that: Iterable<A>): (self: Iterable<A>) => Array<A>;
  <A>(self: Iterable<A>, that: Iterable<A>): Array<A>;
};

Example

import { Array } from "effect"

const difference = Array.difference([1, 2, 3], [2, 3, 4])
console.log(difference) // [1]

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

declare function differenceWith<A>(isEquivalent: (self: A, that: A) => boolean): {
  (that: Iterable<A>): (self: Iterable<A>) => Array<A>;
  (self: Iterable<A>, that: Iterable<A>): Array<A>;
};

extend

Added in v2.0.0 Source

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

Signature

declare const extend: {
  <A, B>(f: (as: readonly Array<A>) => B): (self: readonly Array<A>) => Array<B>;
  <A, B>(self: readonly Array<A>, f: (as: readonly Array<A>) => B): Array<B>;
}

Example

import { Array } from "effect"

const result = Array.extend([1, 2, 3], (as) => as.length)
console.log(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].

forEach

Added in v2.0.0 Source

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

Signature

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"

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

insertAt

Added in v2.0.0 Source

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

Signature

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

Example

import { Array } from "effect"

const result = Array.insertAt(["a", "b", "c", "e"], 3, "d")
console.log(result) // Option.some(['a', 'b', 'c', 'd', 'e'])

intersection

Added in v2.0.0 Source

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

declare const intersection: {
  <B>(that: Iterable<B>): <A>(self: Iterable<A>) => Array<A & B>;
  <A, B>(self: Iterable<A>, that: Iterable<B>): Array<A & B>;
};

Example

import { Array } from "effect"

const result = Array.intersection([1, 2, 3], [3, 4, 1])
console.log(result) // [1, 3]

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

declare function intersectionWith<A>(isEquivalent: (self: A, that: A) => boolean): {
  (that: Iterable<A>): (self: Iterable<A>) => Array<A>;
  (self: Iterable<A>, that: Iterable<A>): Array<A>;
};

intersperse

Added in v2.0.0 Source

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

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

Example

import { Array } from "effect"

const result = Array.intersperse([1, 2, 3], 0)
console.log(result) // [1, 0, 2, 0, 3]

Signature

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

max

Added in v2.0.0 Source

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

Signature

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

Example

import { Array, Order } from "effect"

const result = Array.max([3, 1, 2], Order.number)
console.log(result) // 3

min

Added in v2.0.0 Source

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

Signature

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

Example

import { Array, Order } from "effect"

const result = Array.min([3, 1, 2], Order.number)
console.log(result) // 1

modify

Added in v2.0.0 Source

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

declare const modify: {
  <A, B, S extends Iterable<A, any, any> = Iterable<A, any, any>>(
    i: number,
    f: (a: Infer<S>) => B,
  ): (self: S) => With<S, B | Infer<S>>;
  <A, B, S extends Iterable<A, any, any> = Iterable<A, any, any>>(
    self: S,
    i: number,
    f: (a: Infer<S>) => B,
  ): With<S, B | Infer<S>>;
};

Example

import { Array } from "effect"

const result = Array.modify([1, 2, 3, 4], 2, (n) => n * 2)
console.log(result) // [1, 2, 6, 4]

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

Signature

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

Example

import { Array } from "effect"

const result = Array.modifyNonEmptyHead([1, 2, 3], (n) => n * 10)
console.log(result) // [10, 2, 3]

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

Signature

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

Example

import { Array } from "effect"

const result = Array.modifyNonEmptyLast([1, 2, 3], (n) => n * 2)
console.log(result) // [1, 2, 6]

modifyOption

Added in v2.0.0 Source

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

declare const modifyOption: {
  <A, B, S extends Iterable<A, any, any> = Iterable<A, any, any>>(
    i: number,
    f: (a: Infer<S>) => B,
  ): (self: S) => Option<With<S, B | Infer<S>>>;
  <A, B, S extends Iterable<A, any, any> = Iterable<A, any, any>>(
    self: S,
    i: number,
    f: (a: Infer<S>) => B,
  ): Option<With<S, B | Infer<S>>>;
};

Example

import { Array } from "effect"

const input = [1, 2, 3, 4]
const result = Array.modifyOption(input, 2, (n) => n * 2)
console.log(result) // Option.some([1, 2, 6, 4])

const outOfBoundsResult = Array.modifyOption(input, 5, (n) => n * 2)
console.log(outOfBoundsResult) // Option.none()

pad

Added in v3.8.4 Source

Pads an array. Returns a new array of length n with the elements of array followed by fill elements if array is shorter than n. If array is longer than n, the returned array will be a slice of array containing the n first elements of array. If n is less than or equal to 0, the returned array will be an empty array.

Signature

declare const pad: {
  <A, T>(n: number, fill: T): (self: Array<A>) => Array<A | T>;
  <A, T>(self: Array<A>, n: number, fill: T): Array<A | T>;
};

Example

import { Array } from "effect"

const result = Array.pad([1, 2, 3], 6, 0)
console.log(result) // [1, 2, 3, 0, 0, 0]

remove

Added in v2.0.0 Source

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

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

Example

import { Array } from "effect"

const input = [1, 2, 3, 4]
const result = Array.remove(input, 2)
console.log(result) // [1, 2, 4]

const outOfBoundsResult = Array.remove(input, 5)
console.log(outOfBoundsResult) // [1, 2, 3, 4]

removeOption

Added in v3.16.0 Source

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

Signature

declare const removeOption: {
  (i: number): <A>(self: Iterable<A>) => Option<Array<A>>;
  <A>(self: Iterable<A>, i: number): Option<Array<A>>;
};

Example

import * as assert from "node:assert"
import { Array, Option } from "effect"

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

const outOfBoundsResult = Array.removeOption(numbers, 5)
assert.deepStrictEqual(outOfBoundsResult, Option.none())

replace

Added in v2.0.0 Source

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

declare const replace: {
  <B>(
    i: number,
    b: B,
  ): <A, S extends Iterable<A, any, any> = Iterable<A, any, any>>(self: S) => With<S, B | Infer<S>>;
  <A, B, S extends Iterable<A, any, any> = Iterable<A, any, any>>(
    self: S,
    i: number,
    b: B,
  ): With<S, B | Infer<S>>;
};

Example

import { Array } from "effect"

const result = Array.replace(["a", "b", "c", "d"], 1, "z")
console.log(result) // ['a', 'z', 'c', 'd']

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

Signature

declare const replaceOption: {
  <B>(
    i: number,
    b: B,
  ): <A, S extends Iterable<A, any, any> = Iterable<A, any, any>>(
    self: S,
  ) => Option<With<S, B | Infer<S>>>;
  <A, B, S extends Iterable<A, any, any> = Iterable<A, any, any>>(
    self: S,
    i: number,
    b: B,
  ): Option<With<S, B | Infer<S>>>;
};

Example

import { Array } from "effect"

const result = Array.replaceOption([1, 2, 3], 1, 4)
console.log(result) // Option.some([1, 4, 3])

rotate

Added in v2.0.0 Source

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

Signature

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

Example

import { Array } from "effect"

const result = Array.rotate(["a", "b", "c", "d", "e"], 2)
console.log(result) // [ 'd', 'e', 'a', 'b', 'c' ]

Change the head, creating a new NonEmptyReadonlyArray.

Signature

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

Example

import { Array } from "effect"

const result = Array.setNonEmptyHead([1, 2, 3], 10)
console.log(result) // [10, 2, 3]

Change the last element, creating a new NonEmptyReadonlyArray.

Signature

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

Example

import { Array } from "effect"

const result = Array.setNonEmptyLast([1, 2, 3], 4)
console.log(result) // [1, 2, 4]

union

Added in v2.0.0 Source

Creates a union of two arrays, removing duplicates.

Signature

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

Example

import { Array } from "effect"

const result = Array.union([1, 2], [2, 3])
console.log(result) // [1, 2, 3]

unionWith

Added in v2.0.0 Source

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

Signature

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

Example

import { Array } from "effect"

const union = Array.unionWith([1, 2], [2, 3], (a, b) => a === b)
console.log(union) // [1, 2, 3]

unzip

Added in v2.0.0 Source

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

Signature

declare const unzip: <S extends Iterable<readonly [any, any]>>(
  self: S,
) => S extends NonEmptyReadonlyArray<readonly [infer A, infer B]>
  ? [NonEmptyArray<A>, NonEmptyArray<B>]
  : S extends Iterable<readonly [infer A, infer B]>
    ? [Array<A>, Array<B>]
    : never;

Example

import { Array } from "effect"

const result = Array.unzip([
  [1, "a"],
  [2, "b"],
  [3, "c"],
])
console.log(result) // [[1, 2, 3], ['a', 'b', 'c']]

Pattern Matching

match

Added in v2.0.0 Source

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

Signature

declare const match: {
  <B, A, C = B>(options: {
    readonly onEmpty: LazyArg<B>;
    readonly onNonEmpty: (self: NonEmptyReadonlyArray<A>) => C;
  }): (self: readonly Array<A>) => B | C;
  <A, B, C = B>(self: readonly Array<A>, options: {
    readonly onEmpty: LazyArg<B>;
    readonly onNonEmpty: (self: NonEmptyReadonlyArray<A>) => C;
  }): B | C;
}

Example

import { Array } from "effect"

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

matchLeft

Added in v2.0.0 Source

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

Signature

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

Example

import { Array } from "effect"

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

matchRight

Added in v2.0.0 Source

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

Signature

declare const matchRight: {
  <B, A, C = B>(options: {
    readonly onEmpty: LazyArg<B>;
    readonly onNonEmpty: (init: Array<A>, last: A) => C;
  }): (self: readonly Array<A>) => B | C;
  <A, B, C = B>(self: readonly Array<A>, options: {
    readonly onEmpty: LazyArg<B>;
    readonly onNonEmpty: (init: Array<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}`,
})
console.log(matchRight([])) // "empty"
console.log(matchRight([1, 2, 3])) // "init: 2, last: 3"

Sequencing

flatMap

Added in v2.0.0 Source

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

Signature

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

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

Signature

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

Example

import { Array } from "effect"

const result = Array.flatMapNullable([1, 2, 3], (n) => (n % 2 === 0 ? null : n))
console.log(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].

flatten

Added in v2.0.0 Source

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

declare const flatten: <S extends ReadonlyArray<ReadonlyArray<any>>>(
  self: S,
) => ReadonlyArray.Flatten<S>;

Example

import { Array } from "effect"

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

Sorting

sort

Added in v2.0.0 Source

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

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

sortBy

Added in v2.0.0 Source

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

declare function sortBy<S extends Iterable<any, any, any>>(...orders: readonly Array<Order<Infer<S>>>): (self: S) => S extends readonly [A, A] ? [A, ...Array<A>] : S extends Iterable<A, any, any> ? Array<A> : never

Splitting

chunksOf

Added in v2.0.0 Source

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

``ts skip-type-checking chunksOf(n)(xs).concat(chunksOf(n)(ys)) == chunksOf(n)(xs.concat(ys))) ``

whenever n evenly divides the length of self.

Signature

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

Example

import { Array } from "effect"

const result = Array.chunksOf([1, 2, 3, 4, 5], 2)
console.log(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]]`.

span

Added in v2.0.0 Source

Split an Iterable into two parts:

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

Signature

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

split

Added in v2.0.0 Source

Splits this iterable into n equally sized arrays.

Signature

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

Example

import { Array } from "effect"

const result = Array.split([1, 2, 3, 4, 5, 6, 7, 8], 3)
console.log(result) // [[1, 2, 3], [4, 5, 6], [7, 8]]

splitAt

Added in v2.0.0 Source

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

Signature

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

Example

import { Array } from "effect"

const result = Array.splitAt([1, 2, 3, 4, 5], 3)
console.log(result) // [[1, 2, 3], [4, 5]]

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

Signature

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

Example

import { Array } from "effect"

const result = Array.splitNonEmptyAt(["a", "b", "c", "d", "e"], 3)
console.log(result) // [["a", "b", "c"], ["d", "e"]]

splitWhere

Added in v2.0.0 Source

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

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

Example

import { Array } from "effect"

const result = Array.splitWhere([1, 2, 3, 4, 5], (n) => n > 3)
console.log(result) // [[1, 2, 3], [4, 5]]

unappend

Added in v2.0.0 Source

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

Signature

declare function unappend<A>(
  self: readonly [A, A],
): [arrayWithoutLastElement: Array<A>, lastElement: A];

unprepend

Added in v2.0.0 Source

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

Signature

declare function unprepend<A>(
  self: readonly [A, A],
): [firstElement: A, remainingElements: Array<A>];

window

Added in v3.13.2 Source

Creates sliding windows of size n from an Iterable. If the number of elements is less than n or if n is not greater than zero, an empty array is returned.

Signature

declare const window: {
  <N extends number = number>(n: N): <A>(self: Iterable<A>) => Array<TupleOf<N, A>>;
  <A, N extends number = number>(self: Iterable<A>, n: N): Array<TupleOf<N, A>>;
};

Example

import * as assert from "node:assert"
import { Array } from "effect"

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

Type Lambdas

ReadonlyArrayTypeLambda interface

Added in v2.0.0 Source

Signature

interface ReadonlyArrayTypeLambda extends TypeLambda {
  readonly type: readonly Array<unknown>;
}

Unsafe

unsafeGet

Added in v2.0.0 Source

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

Signature

declare const unsafeGet: {
  (index: number): <A>(self: readonly Array<A>) => A;
  <A>(self: readonly Array<A>, index: number): A;
}

Zipping

zip

Added in v2.0.0 Source

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

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

Example

import { Array } from "effect"

const result = Array.zip([1, 2, 3], ["a", "b"])
console.log(result) // [[1, 'a'], [2, 'b']]

zipWith

Added in v2.0.0 Source

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

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

Example

import { Array } from "effect"

const result = Array.zipWith([1, 2, 3], [4, 5, 6], (a, b) => a + b)
console.log(result) // [5, 7, 9]