Jagadeesh Govindaraj Jagadeesh Govindaraj - 1 month ago 21
TypeScript Question

Typescript swap array Items

how to swap two elements using typescript

elements:elements[] =[];
elements.push(item1);
elements.push(item2);
elements.push(item3);
elements.push(item4);


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
array.swap()

Answer

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) {
        return
    }

    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;
    }
}