Note: You may want to add additional checks for example for array length. This solution is mutable so swap function does not need to return a new array, it just does mutation over array passed into.
For the sake of brevity, here's the ugly one-liner version that's only slightly less ugly than all that concat and slicing above. The accepted answer is truly the way to go and way more readable.
Given:
var foo = [ 0, 1, 2, 3, 4, 5, 6 ];
if you want to swap the values of two indices (a and b); then this would do it:
foo.splice( a, 1, foo.splice(b,1,foo[a])[0] );
For example, if you want to swap the 3 and 5, you could do it this way:
Here is a variation that first checks if the index exists in the array:
It currently will just return
this
if the index does not exist, but you could easily modify behavior on failConsider such a solution without a need to define the third variable:
Note: You may want to add additional checks for example for array length. This solution is mutable so
swap
function does not need to return a new array, it just does mutation over array passed into.This didn't exist when the question was asked, but ES2015 introduced array destructuring, allowing you to write it as follows:
For the sake of brevity, here's the ugly one-liner version that's only slightly less ugly than all that concat and slicing above. The accepted answer is truly the way to go and way more readable.
Given:
if you want to swap the values of two indices (a and b); then this would do it:
For example, if you want to swap the 3 and 5, you could do it this way:
or
Both yield the same result:
#splicehatersarepunks:)
Digest from http://www.greywyvern.com/?post=265
If need swap first and last elements only: