814Swapping Array Items in Javascript
var myArray = ["a", "c", "b"];
myArray.swap(1, 2);
console.log(myArray);
// ["a", "b", "c"];
Array.prototype.swap=function(a, b) {
this[a]= this.splice(b, 1, this[a])[0];
return this;
}
It could also be done with a temp var, but this solution seems to be the most elegant. The key to this is in the additional arguments the splice() function can accept.
splice(start, itemCount, additionalItems ...)
splice() removes elements denominated by the start and itemCount argument, and - if specified - inserts additional items at the same position.
Also important to note is that splice() returns an array. And to turn that array into an item again we need to select it directly with [0].