Javascript swap array elements

Javascript swap array elements

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;

Solutions/Answers:

Solution 1:

You only need one temporary variable.

var b = list[y];
list[y] = list[x];
list[x] = b;

Edit hijacking top answer 10 years later with a lot of ES6 adoption under our belts:

Given the array arr = [1,2,3,4], you can swap values in one line now like so:

[arr[0], arr[1]] = [arr[1], arr[0]];

This would produce the array [2,1,3,4]. This is destructuring assignment.

Solution 2:

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])[0];
alert(A); // alerts "2,1,3,4,5,6,7,8,9"

Edit:

The [0] is necessary at the end of the expression as Array.splice() returns an array, and in this situation we require the single element in the returned array.

Related:  What is two way binding?

Solution 3:

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.

Solution 4:

According to some random person on Metafilter,
“Recent versions of Javascript allow you to do swaps (among other things) much more neatly:”

[ list[x], list[y] ] = [ list[y], list[x] ];

My quick tests showed that this Pythonic code works great in the version of JavaScript
currently used in “Google Apps Script” (“.gs”).
Alas, further tests show this code gives a “Uncaught ReferenceError: Invalid left-hand side in assignment.” in
whatever version of JavaScript (“.js”) is used by
Google Chrome Version 24.0.1312.57 m.

Related:  Does Phantom.js capture all AJAX?

Solution 5:

Well, you don’t need to buffer both values – only one:

var tmp = list[x];
list[x] = list[y];
list[y] = tmp;

Solution 6:

You can swap elements in an array the following way:

list[x] = [list[y],list[y]=list[x]][0]

See the following example:

list = [1,2,3,4,5]
list[1] = [list[3],list[3]=list[1]][0]
//list is now [1,4,3,2,5]

Note: it works the same way for regular variables

var a=1,b=5;
a = [b,b=a][0]