views:

3226

answers:

5

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;
+7  A: 

You only need one temporary variable.

var b = list[y];
list[y] = list[x];
list[x] = b;
tvanfosson
+5  A: 

Well, you don't need to buffer both values - only one:

var tmp = list[x];
list[x] = list[y];
list[y] = tmp;
Marc Gravell
your 'tmp' sounds more reasonable to use then 'b'
mtasic
+2  A: 

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];
Darth
Is that darth as in vader ? +1
krosenvold
That only works with numeric values though, doesn't it?
Dan Herbert
It would work with any binary values of the same length.
Stephen Holiday
+2  A: 

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.

NixNinja
I like this also. Array.implement({ swap: function(x,y) { x = this[x]; this[x] = this[y]; this[y] = x; return this; } });
ken
that seems library dependent?
NixNinja
+5  A: 

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"

kennebec
splice returns an array. So in your example, after the swap operation your array actually looks like: [[2], 1, 3, 4, 5, 6, 7, 8, 9]
JPot
A[x]= A.splice(y, 1, A[x])[0]; ? in mootoolsArray.implement({ swap: function(x, y) { this[y] = this.splice(x, 1, this[y])[0]; }});
ken
Confirmed, the [0] is missing.
Johann Philipp Strathausen