Array
arrayInsert

📥 Inserts items at the specified index into an array.

Immutable: This function does not mutate the original array.

Syntax

import { arrayInsert } from '@opentf/std';
 
arrayInsert<T>(
  arr: T[] = [],
  index: number | null | undefined,
  ...items: T[]
): T[]

Parameters

  • arr: The source array.
  • index: The index where the new items should be inserted. If null or undefined, items are appended to the end.
  • ...items: The items to be inserted.

Returns

A new array with the inserted items.

Examples

arrayInsert([]) //=> []
 
arrayInsert([1]) //=> [1]
 
arrayInsert([1], 0) //=> [1]
 
arrayInsert([1], 0, 0) //=> [0, 1]
 
arrayInsert([1], 1, 0) //=> [1, 0]
 
arrayInsert([1, 2, 3], 1, 5) //=> [1, 5, 2, 3]
 
arrayInsert([1, 2, 3], -1, 5) //=> [1, 2, 5, 3]
 
arrayInsert([1, 2, 3], -3, 5) //=> [5, 1, 2, 3]
 
arrayInsert([1, 2, 3], 3, 5) //=> [1, 2, 3, 5]
 
arrayInsert([1, 2, 3], 3, 5, 6) //=> [1, 2, 3, 5, 6]
 
arrayInsert([1, 2, 3], null, 5, 6) //=> [1, 2, 3, 5, 6]
 
arrayInsert([1, 2, 3], 0, [5, 6]) //=> [[5, 6], 1, 2, 3]
 
arrayInsert([1, 2, 3], 0, ...[5, 6]) //=> [5, 6, 1, 2, 3]

Related

Try