🔄 Replaces items at the specified index in an array.

Info

Immutable: This function does not mutate the original array.

Syntax

TypeScript
import { replace } from '@opentf/std';

replace<T>(
  arr: T[] = [],
  indexOrFn: number | null | ((item: T, index: number, array: T[]) => boolean),
  ...items: T[]
): T[]

Parameters

  • arr: The source array.

  • indexOrFn: The index at which to start replacing items, or a predicate function to replace all matching items. If null, it defaults to the last index.

  • ...items: The items to replace with. When using a predicate, all matching items are replaced with the first item.

Returns

A new array with the items replaced.

Examples

TypeScript
replace([]) //=> []

replace([1]) //=> [1]

replace([1, 2, 3], 0, 1, 'a') //=> ['a', 2, 3]

replace([1, 2, 3], null, 1, 'a') //=> [1, 2, 'a']

replace([1, 2, 3], 3, null, 'c') //=> [1, 2, 3, 'c']

const months = ['Jan', 'Feb', 'Apr', 'May'];
replace(months, 1, 1, 'Feb', 'Mar') //=> ['Jan', 'Feb', 'Mar', 'Apr', 'May']

replace(months, 1, null, 'Feb', 'Mar') //=> ['Jan', 'Feb', 'Mar', 'May']

// Predicate-based replace
replace([1, 2, 3, 4, 5], (x) => x % 2 === 0, 0) //=> [1, 0, 3, 0, 5]
Last updated on
Edit this page