Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 item1 
elements[3] is item4

How can i interchange these items in typescript. i know Javascript way, like this:

*javascript example using temp variable *

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

but there is any api doing same thing in typescript like array.swap()

like image 796
Jagadeesh Govindaraj Avatar asked Nov 10 '16 09:11

Jagadeesh Govindaraj


3 Answers

Why not use destructuring and an array.

[elements[0], elements[3]] = [elements[3], elements[0]];
like image 90
Nina Scholz Avatar answered Jan 21 '23 00:01

Nina Scholz


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;
    }
}
like image 31
Nitzan Tomer Avatar answered Jan 21 '23 01:01

Nitzan Tomer


swapArray(Array:any,Swap1:number,Swap2:number) : any
{
    var temp = Array[Swap1];
    Array[Swap1] = Array[Swap2]
    Array[Swap2] = temp
    return Array;
}
like image 20
Kapein Avatar answered Jan 21 '23 01:01

Kapein