8

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()

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
Jagadeesh Govindaraj
  • 6,977
  • 6
  • 32
  • 52
  • not the answer you look for, but it seems like the javascript example is the usual example http://stackoverflow.com/questions/872310/javascript-swap-array-elements http://stackoverflow.com/questions/4011629/swapping-two-items-in-a-javascript-array https://www.kirupa.com/html5/swapping_items_array_js.htm – Kapein Nov 10 '16 at 09:29
  • @Kapein i know plain javascript do it simple, but i can know any api doing this in typescript? did you get my point – Jagadeesh Govindaraj Nov 10 '16 at 09:34
  • the angular 2 version of this? – Kapein Nov 10 '16 at 09:35
  • 1
    TS doesn't have any special API. It is typed JS. – Estus Flask Nov 10 '16 at 09:35

5 Answers5

59

Why not use destructuring and an array.

[elements[0], elements[3]] = [elements[3], elements[0]];
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 6
    This is the correct answer. See array destructing topic here: https://www.typescriptlang.org/docs/handbook/variable-declarations.html – rmcsharry Oct 16 '17 at 14:20
  • This does not work with the noUncheckedIndexedAccess compiler option. – Marcel Apr 15 '22 at 10:41
4

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;
    }
}
Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
  • 2
    In typescript there is inbuilt functionality for it. It's called array destructuring - see the answer from Nina – rmcsharry Oct 16 '17 at 14:22
  • @rmcsharry That's not the same. What if you do not want to create a new instance and want to swap within the array itself? – Nitzan Tomer Oct 16 '17 at 14:25
  • that is exactly what Nina's answer shows - no new instance is being created, data is being swapped within the array itself. – rmcsharry Oct 16 '17 at 15:40
  • @rmcsharry you're right, my bad, I didn't pay much attention to it. – Nitzan Tomer Oct 16 '17 at 16:42
  • @rmcsharry Ok, so now that I actually had time to revue the question and the answers more thoroughly, the OP asked for "and api like array.swap()", which is what I gave him. You can argue that maybe the implementation of the method itself should have used the destructuring way, but that isn't the main part of my answer. – Nitzan Tomer Oct 16 '17 at 17:20
  • fair enough, but the OP also asked "How can i interchange these items in typescript" so both answers are correct, since there are actually 2 questions ;) – rmcsharry Oct 16 '17 at 17:55
4
swapArray(Array:any,Swap1:number,Swap2:number) : any
{
    var temp = Array[Swap1];
    Array[Swap1] = Array[Swap2]
    Array[Swap2] = temp
    return Array;
}
Kapein
  • 175
  • 13
1

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.

rmcsharry
  • 5,363
  • 6
  • 65
  • 108
1

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.

A benchmark

The result is de-structuring is an order of magnitude slower than the temp method.

enter image description here

vykaash
  • 56
  • 4
  • 1
    Thank you for your answer and the comparison. Could you add the benchmark results to your answer as well? A link to the benchmark is fine but the answer would become useless if the link stops working in the future – Michael Kotzjan Oct 14 '21 at 07:29