Jagadeesh Govindaraj Jagadeesh Govindaraj - 1 year ago 368
TypeScript Question

Typescript swap array Items

how to swap two elements using typescript

elements:elements[] =[];

elements[0] is item 1
element[3] is item 3

how can i interchange this items in typescript, i know java script way.like this

javascript example

var tmp = elements[0];
elements[0] = elements[3];
elements[3] = tmp;

but there is any api doing same thing in typescript like

Answer Source

There's no builtin functionality for it, but you can easily add it:

interface Array<T> {
    swap(a: number, b: number): void;

Array.prototype.swap = function (a: number, b: number) {
    if (a < 0 || a >= this.length || b < 0 || b >= this.length) {

    const temp = this[a];
    this[a] = this[b];
    this[b] = temp;

(code in playground)

If you are using modules then you'll need to do this to augment the Array interface:

declare global {
    interface Array<T> {
        swap(a: number, b: number): void;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download