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;
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.
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.