Reputation: 8305
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()
Upvotes: 9
Views: 28514
Reputation: 96
This question is old but if you're like me you may have come across this post checking for built in swap behavior.
The accepted answer uses de-structuring, and it's fine but it is slower than using a temp to swap elements. If performance is a concern use the temp method as OP has described.
The result is de-structuring is an order of magnitude slower than the temp method.
Upvotes: 1
Reputation: 5562
You can do this in one line in Javascript (and therefore Typescript, although in Typescript you can do array destructure as shown in another answer).
For primitive types (eg. integers, strings) you can do this to swap simple values a and b around (credit here):
a = [b, b=a][0];
So if you had an array with 3 elements, like so: a=['me','you','us']
You can swap 'me' and 'you' like this:
a = [a[1],a[1]=a[0],a[2]]
So taking the OP's 4 element array, to swap the first (0th) and last (3rd) elements, you would do:
elements = [elements[3],elements[1],elements[2],elements[3]=elements[0]]
However, that is not easy to understand code, so I don't recommend it. Using a tmp variable is more straightforward. Also, it's not very performant or maintainable since you have to specify every element of the original array.
Upvotes: 1
Reputation: 175
swapArray(Array:any,Swap1:number,Swap2:number) : any
{
var temp = Array[Swap1];
Array[Swap1] = Array[Swap2]
Array[Swap2] = temp
return Array;
}
Upvotes: 4
Reputation: 164217
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;
}
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;
}
}
Upvotes: 4
Reputation: 386654
Why not use destructuring and an array.
[elements[0], elements[3]] = [elements[3], elements[0]];
Upvotes: 62