Search code examples
javascriptangulartypescriptdestructuring

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


Solution

  • Why not use destructuring and an array.

    [elements[0], elements[3]] = [elements[3], elements[0]];