Skip to content

swap ​

The swap function exchanges the elements at two positions in an array.

Syntax ​

typescript
swap<T>(array: T[], indexA: number, indexB: number): T[];

Parameters ​

NameTypeDescription
arrayT[]Source array
indexAnumberIndex of the first element
indexBnumberIndex of the second element

Returns ​

TypeDescription
T[]New array with swapped elements

Examples ​

typescript
swap([1, 2, 3, 4], 0, 2); // => [3, 2, 1, 4]

Notes ​

  • Does not modify the original array.
  • If the indices are the same, returns the array unchanged.

References ​

Released under the MIT License.