replace

🔄 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),
  options?: { 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.

  • options.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, { items: ['a'] }) //=> ['a', 2, 3]

replace([1, 2, 3], null, { items: ['a'] }) //=> [1, 2, 'a']

replace([1, 2, 3], 3, { items: ['c'] }) //=> [1, 2, 3, 'c']

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

replace(months, 1, { items: ['Feb'] }) //=> ['Jan', 'Feb', 'Apr', 'May']

// Predicate-based replace
replace([1, 2, 3, 4, 5], (x) => x % 2 === 0, { items: [0] }) //=> [1, 0, 3, 0, 5]

Try it

Last updated on
Edit this page