Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; 
like image 549
ken Avatar asked May 16 '09 12:05

ken


People also ask

Is there a swap function in Javascript?

Here, a new es6 feature, called destructuring assignment [a, b] = [b, a] , is used to swap the value of two variables. If [a, b] = [1, 2, 3] , the value of a will be 1 and value of b will be 2. First a temporary array [b, a] is created.


1 Answers

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.

like image 140
tvanfosson Avatar answered Oct 15 '22 13:10

tvanfosson