Is there any simpler way to swap two elements in an array?
var a = list[x], b = list[y];
list[y] = a;
list[x] = b;
Is there any simpler way to swap two elements in an array?
var a = list[x], b = list[y];
list[y] = a;
list[x] = b;
You only need one temporary variable.
var b = list[y];
list[y] = list[x];
list[x] = b;
Well, you don't need to buffer both values - only one:
var tmp = list[x];
list[x] = list[y];
list[y] = tmp;
Or you can do it nasty with bitwise xor
list[x] = list[x] ^ list[y];
list[y] = list[y] ^ list[x];
list[x] = list[x] ^ list[y];
This seems ok....
var b = list[y];
list[y] = list[x];
list[x] = b;
Howerver using
var b = list[y];
means a b variable is going to be to be present for the rest of the scope. This can potentially lead to a memory leak. Unlikely, but still better to avoid.
Maybe a good idea to put this into Array.prototype.swap
Array.prototype.swap = function (x,y) {
var b = this[x];
this[x] = this[y];
this[y] = b;
return this;
}
which can be called like:
list.swap( x, y )
This is a clean approach to both avoiding memory leaks and DRY.
If you want a single expression, using native javascript, remember that the return value from a splice operation contains the element(s) that was removed.
var A= [1, 2, 3, 4, 5, 6, 7, 8, 9], x= 0, y= 1;
A[x]= A.splice(y, 1, A[x]);
alert(A) // alerts"2,1,3,4,5,6,7,8,9"