303

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;
ken
  • 4,496
  • 4
  • 29
  • 25

33 Answers33

608

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.

temporary_user_name
  • 33,659
  • 44
  • 133
  • 199
tvanfosson
  • 509,016
  • 97
  • 693
  • 791
  • 6
    Even without utilizing ECMAScript 6 Destructuring Assignment, can actually achieve a simultaneous swap without polluting the current scope with a temporary variable: `a = [b, b = a][0];` as pointed out by @Jan Although I still find myself utilizing the temporary variable approach as it's cross-language (e.g. C/C++) and the first approach that usually pops into my mind. – Ultimater Aug 15 '18 at 07:22
  • 5
    You can swap in place (mutate) with es6 as others show below: `[ list[y], list[x] ] = [ list[x], list[y] ];` – protoEvangelion Dec 15 '18 at 18:28
  • `[arr[0], arr[1]] = [arr[1], arr[0]]` produce only `[2, 1]` without the rest of the array – Yerko Palma Sep 04 '19 at 16:03
  • 11
    @YerkoPalma - the expression returns [2,1], but the original array will be mutated to [2,1,3,4] – danbars Sep 12 '19 at 08:45
  • 5
    In that case the es6 expression is likely inefficient as it is generating a new and unnecessary array allocation. – Chris_F Jul 12 '20 at 23:53
  • 2
    Can someone explain to me why `[arr[1], arr[0]]` mutates the original array? This seems incredible unreadable to me. – jajabarr Oct 18 '21 at 00:08
124

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.

Riking
  • 2,281
  • 1
  • 21
  • 35
kennebec
  • 98,993
  • 30
  • 103
  • 125
83

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.

Stefan
  • 8,670
  • 6
  • 36
  • 46
  • I like this also. Array.implement({ swap: function(x,y) { x = this[x]; this[x] = this[y]; this[y] = x; return this; } }); – ken May 17 '09 at 06:23
  • 1
    This is nice. Maybe some bounds checking? `Array.prototype.swap = function (x,y) { if (x >= 0 && x < this.length && y >= 0 && y < this.length) { var b = this[x]; this[x] = this[y]; this[y] = b; } return this; };` – David R. Oct 12 '15 at 16:49
  • @DavidR. Bounds checking is superfluous and unnecessary. The caller has everything necessary to perform such a check if that is desired, though in most cases you already know x and y are in bounds because you're in a loop of some sort. – Neil Dec 11 '15 at 16:00
  • adding the Array.prototype and using .swap() worked really well for me. thanks for sharing! – Elon Zito Feb 15 '16 at 04:14
  • 6
    Couldn't you avoid the "potential memory leak" by just wrapping it in a function? – Carcigenicate Feb 16 '16 at 16:34
  • Could get away with using let – The Prophet Mar 02 '17 at 16:41
  • 4
    To avoid the potential "flatten" mishap, I wouldn't touch the prototype chain of any built-in types. – AaronDancer Apr 12 '18 at 22:02
78

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.

Community
  • 1
  • 1
David Cary
  • 5,001
  • 6
  • 52
  • 63
31

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

var tmp = list[x];
list[x] = list[y];
list[y] = tmp;
Marc Gravell
  • 976,458
  • 251
  • 2,474
  • 2,830
26

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]
Jan
  • 536
  • 6
  • 16
  • 6
    This is strikingly similar to the standard correct way to do this in ES6 (next version of JavaScript): `[list[x], list[y]] = [list[y], list[x]];`. – Isiah Meadows May 03 '14 at 23:27
  • 1
    This has got nothing to do we ES6 array swap by de-structuring. This is just a clever use of JS workflow. A beautiful swap pattern if you use inline coding frequently, such as `this[0] > this[1] && (this[0] = [this[1],this[1]=this[0]][0]);` – Redu Aug 29 '16 at 12:36
22

This didn't exist when the question was asked, but ES2015 introduced array destructuring, allowing you to write it as follows:

let a = 1, b = 2;
// a: 1, b: 2
[a, b] = [b, a];
// a: 2, b: 1
Pieter De Clercq
  • 1,883
  • 1
  • 15
  • 27
dirkdig
  • 489
  • 3
  • 8
18

Consider such a solution without a need to define the third variable:

function swap(arr, from, to) {
  arr.splice(from, 1, arr.splice(to, 1, arr[from])[0]);
}

var letters = ["a", "b", "c", "d", "e", "f"];

swap(letters, 1, 4);

console.log(letters); // ["a", "e", "c", "d", "b", "f"]

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.

Shevchenko Viktor
  • 4,350
  • 2
  • 16
  • 25
17

To swap two consecutive elements of array

array.splice(IndexToSwap,2,array[IndexToSwap+1],array[IndexToSwap]);
Piyush Madan
  • 181
  • 2
  • 4
17

With numeric values you can avoid a temporary variable by using bitwise xor

list[x] = list[x] ^ list[y];
list[y] = list[y] ^ list[x];
list[x] = list[x] ^ list[y];

or an arithmetic sum (noting that this only works if x + y is less than the maximum value for the data type)

list[x] = list[x] + list[y];
list[y] = list[x] - list[y];
list[x] = list[x] - list[y];
ErikE
  • 46,564
  • 22
  • 147
  • 188
Jakub Arnold
  • 83,249
  • 86
  • 225
  • 325
  • 2
    Is that darth as in vader ? +1 – krosenvold May 16 '09 at 12:34
  • 7
    Something is wrong. Doesn't `list[y] = list[x] - list[x];` just equate to `list[y] = 0;`? – ErikE Dec 09 '12 at 07:59
  • 3
    The xor trick also fails when x=y -- it sets list[x] to zero, when you might expect it to keep list[x] the original value. – David Cary Feb 14 '13 at 17:51
  • @ErikE I just submitted a fix. You can replace that line with `list[y] = -1 * (list[y] - list[x]);` and make it work. – webXL Aug 13 '14 at 14:56
  • @webXL do you mean `list[y] = list[x] - list[y]`? There's no reason to negate the negation. – ErikE Aug 13 '14 at 16:14
  • @ErikE you're right. For some reason `list[y] = list[x] - list[y]; list[x] = list[x] - list[y]`; didn't look right to me, since the operands are duplicated, but list[y] holds the swapped value in the second one. Thanks. – webXL Aug 14 '14 at 16:39
  • 2
    Technically you make a temp value you just dont move it outside the relevant area of the array. – Mark Smit Jul 30 '15 at 11:39
  • 2
    Neither simpler, neither more efficient, neither generic. – LoganMzz Aug 10 '17 at 13:43
  • but less memory consuming xD – Kamil Kiełczewski Feb 06 '18 at 16:46
  • 1
    This might be acceptable in C, but it's not good Javascript. It can only be treated as a swap if certain properties can be guaranteed about the elements, e.g. they are both ints. Even with the arithmetic version, there's a good chance of precision loss with floats. And yes, it's also horribly unclear. At least the initial version of this answer admitted it was nasty. – mwfearnley Sep 23 '19 at 20:59
14

For two or more elements (fixed number)

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

No temporary variable required!

I was thinking about simply calling list.reverse().
But then I realised it would work as swap only when list.length = x + y + 1.

For variable number of elements

I have looked into various modern Javascript constructions to this effect, including Map and map, but sadly none has resulted in a code that was more compact or faster than this old-fashioned, loop-based construction:

function multiswap(arr,i0,i1) {/* argument immutable if string */
    if (arr.split) return multiswap(arr.split(""), i0, i1).join("");
    var diff = [];
    for (let i in i0) diff[i0[i]] = arr[i1[i]];
    return Object.assign(arr,diff);
}

Example:
    var alphabet = "abcdefghijklmnopqrstuvwxyz";
    var [x,y,z] = [14,6,15];
    var output = document.getElementsByTagName("code");
    output[0].innerHTML = alphabet;
    output[1].innerHTML = multiswap(alphabet, [0,25], [25,0]);
    output[2].innerHTML = multiswap(alphabet, [0,25,z,1,y,x], [25,0,x,y,z,3]);
<table>
    <tr><td>Input:</td>                        <td><code></code></td></tr>
    <tr><td>Swap two elements:</td>            <td><code></code></td></tr>
    <tr><td>Swap multiple elements:&nbsp;</td> <td><code></code></td></tr>
</table>
Community
  • 1
  • 1
7vujy0f0hy
  • 7,492
  • 1
  • 25
  • 31
14

what about Destructuring_assignment

var arr = [1, 2, 3, 4]
[arr[index1], arr[index2]] = [arr[index2], arr[index1]]

which can also be extended to

[src order elements] => [dest order elements]
ROROROOROROR
  • 871
  • 1
  • 13
  • 31
12

Digest from http://www.greywyvern.com/?post=265

var a = 5, b = 9;    
b = (a += b -= a) - b;    
alert([a, b]); // alerts "9, 5"
R-way Orz
  • 153
  • 1
  • 3
  • 1
    If you wrap this in a `swap(a, b)` function you don't need to worry about readability. – AccidentalTaylorExpansion Jun 23 '16 at 08:47
  • 1
    Works only for integers – Redu Aug 29 '16 at 12:28
  • This probably optimises poorly. A compiler might detect it as a "swap idiom", but can't be sure of the effects unless it can be sure that both types are ints, and also that they don't [alias](https://en.wikipedia.org/wiki/XOR_swap_algorithm#Aliasing). – mwfearnley Sep 23 '19 at 21:14
7

You can swap any number of objects or literals, even of different types, using a simple identity function like this:

var swap = function (x){return x};
b = swap(a, a=b);
c = swap(a, a=b, b=c);

For your problem:

var swap = function (x){return x};
list[y]  = swap(list[x], list[x]=list[y]);

This works in JavaScript because it accepts additional arguments even if they are not declared or used. The assignments a=b etc, happen after a is passed into the function.

dansalmo
  • 10,936
  • 5
  • 55
  • 50
  • Hackish...but you could do one better, if you are only using the function once: `list[y] = (function(x){return x})(list[x],list[x]=list[y]);`. Or, if you're interested in ES6 (next version of JS), it's insanely easy: `[list[x], list[y]] = [list[y], list[x]`. I'm so glad they are adding some more functional and class-based aspects into the next version of JavaScript. – Isiah Meadows May 03 '14 at 23:22
7

There is one interesting way of swapping:

var a = 1;
var b = 2;
[a,b] = [b,a];

(ES6 way)

Vivek
  • 4,566
  • 2
  • 16
  • 27
6

Here's a one-liner that doesn't mutate list:

let newList = Object.assign([], list, {[x]: list[y], [y]: list[x]})

(Uses language features not available in 2009 when the question was posted!)

fmg
  • 709
  • 6
  • 14
3

var arr = [1, 2];
arr.splice(0, 2, arr[1], arr[0]);
console.log(arr); //[2, 1]
  • 2
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Alessio Aug 07 '19 at 10:42
3
var a = [1,2,3,4,5], b=a.length;

for (var i=0; i<b; i++) {
    a.unshift(a.splice(1+i,1).shift());
}
a.shift();
//a = [5,4,3,2,1];
Nathan Romano
  • 6,908
  • 3
  • 17
  • 18
2

Here's a compact version swaps value at i1 with i2 in arr

arr.slice(0,i1).concat(arr[i2],arr.slice(i1+1,i2),arr[i1],arr.slice(i2+1))
Tibos
  • 26,984
  • 4
  • 46
  • 61
  • That is less efficient then the temporary variable method. You're effectively returning a modified array that was sliced three times and concatenated together with two objects between the three sliced arrays. You've effectively required more than twice the memory than necessary to get the value to simply assign to the array (none of that was done in place). – Isiah Meadows May 03 '14 at 23:33
2

Flow

not inplace solution

let swap= (arr,i,j)=> arr.map((e,k)=> k-i ? (k-j ? e : arr[i]) : arr[j]);

let swap= (arr,i,j)=> arr.map((e,k)=> k-i ? (k-j ? e : arr[i]) : arr[j]);


// test index: 3<->5 (= 'f'<->'d')
let a= ["a","b","c","d","e","f","g"];
let b= swap(a,3,5);

console.log(a,"\n", b);
console.log('Example Flow:', swap(a,3,5).reverse().join('-') );

and inplace solution

let swap= (arr,i,j)=> {let t=arr[i]; arr[i]=arr[j]; arr[j]=t; return arr}


// test index: 3<->5 (= 'f'<->'d')
let a= ["a","b","c","d","e","f","g"];

console.log( swap(a,3,5) )
console.log('Example Flow:', swap(a,3,5).reverse().join('-') );

In this solutions we use "flow pattern" which means that swap function returns array as result - this allow to easily continue processing using dot . (like reverse and join in snippets)

Kamil Kiełczewski
  • 71,169
  • 26
  • 324
  • 295
1

Here is a variation that first checks if the index exists in the array:

Array.prototype.swapItems = function(a, b){
    if(  !(a in this) || !(b in this) )
        return this;
    this[a] = this.splice(b, 1, this[a])[0];
    return this;
}

It currently will just return this if the index does not exist, but you could easily modify behavior on fail

Douglas.Sesar
  • 3,874
  • 3
  • 27
  • 36
1

If you don't want to use temp variable in ES5, this is one way to swap array elements.

var swapArrayElements = function (a, x, y) {
  if (a.length === 1) return a;
  a.splice(y, 1, a.splice(x, 1, a[y])[0]);
  return a;
};

swapArrayElements([1, 2, 3, 4, 5], 1, 3); //=> [ 1, 4, 3, 2, 5 ]
venkat7668
  • 2,477
  • 1
  • 20
  • 24
  • This way, instead of creating a temp variable you are creating 2 new arrays as `a.splice` returns an array with the removed elements. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice – XCS Mar 25 '19 at 09:51
  • Is there any way that we can do it better? @Cristy – venkat7668 Mar 25 '19 at 16:36
  • Accepted answer is straight forward one. This will be handy when you have a limitation on number of variables declaration (mostly interview purpose :) ). But not memory efficient as you mentioned. @Cristy – venkat7668 Mar 27 '19 at 09:46
  • I personally think it's a bad practice and should not be recommended to beginners. It's also very hard to read. – XCS Mar 27 '19 at 12:32
1

Typescript solution that clones the array instead of mutating existing one

export function swapItemsInArray<T>(items: T[], indexA: number, indexB: number): T[] {
  const itemA = items[indexA];

  const clone = [...items];

  clone[indexA] = clone[indexB];
  clone[indexB] = itemA;

  return clone;
}
Adam Pietrasiak
  • 11,708
  • 7
  • 73
  • 89
0
Array.prototype.swap = function(a, b) {
  var temp = this[a];
  this[a] = this[b];
  this[b] = temp;
};

Usage:

var myArray = [0,1,2,3,4...];
myArray.swap(4,1);
Pryme8
  • 133
  • 10
  • 1
    No need to be rude. Also, extending the `Array` prototype was not part of what was asked for - it may confuse more than it does good. – Mathias Lykkegaard Lorenzen Oct 16 '16 at 15:40
  • How is expressing that some of the answers are crazy and extending the array prototype would be and adding a return this would make it chain able... – Pryme8 Oct 17 '16 at 22:47
  • 2
    You are expressing it as "the correct way". It may give the wrong impression. Instead, I would suggest mentioning what you are doing (extending the prototype), and how it is useful, exactly as you just described to me. – Mathias Lykkegaard Lorenzen Oct 18 '16 at 05:16
  • 1
    gotcha, sorry my poise is not on pair sometimes ^_^ – Pryme8 Oct 27 '16 at 18:50
  • -6 y'all are crazy. – Pryme8 Aug 10 '17 at 23:53
  • Well then maybe consider deleting your answer, or following the advice of people describing why they gave you the vote they did. – Mathias Lykkegaard Lorenzen Aug 17 '17 at 11:31
  • 3
    You are the only one describing a problem with the context of the answer... first off negative scores should be reserved for non working answers. Second this is a good answer with an elegant usage that causes no conflicts. Judge the code not the delivery. Also in my answer if you stripped it down and excluded the prototype extension it becomes the exacts same as the most up voted answer, so the fact that this is -6 shows the lack of thought from the people who voted it down. And was posted months before the top answer... so this sounds like a popularity not a code contest. – Pryme8 Aug 18 '17 at 15:24
0

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:

foo.splice( 3, 1, foo.splice(5,1,foo[3])[0] );

or

foo.splice( 5, 1, foo.splice(3,1,foo[5])[0] );

Both yield the same result:

console.log( foo );
// => [ 0, 1, 2, 5, 4, 3, 6 ]

#splicehatersarepunks:)

Jasonovich
  • 597
  • 4
  • 11
0

Swap the first and last element in an array without temporary variable or ES6 swap method [a, b] = [b, a]

[a.pop(), ...a.slice(1), a.shift()]

gengns
  • 1,382
  • 12
  • 20
0
function moveElement(array, sourceIndex, destinationIndex) {
    return array.map(a => a.id === sourceIndex ? array.find(a => a.id === destinationIndex): a.id === destinationIndex ? array.find(a => a.id === sourceIndex) : a )
}
let arr = [
{id: "1",title: "abc1"},
{id: "2",title: "abc2"},
{id: "3",title: "abc3"},
{id: "4",title: "abc4"}];

moveElement(arr, "2","4");
  • 4
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Jul 18 '20 at 10:14
0

in place swap

// array methods
function swapInArray(arr, i1, i2){
    let t = arr[i1];
    arr[i1] = arr[i2];
    arr[i2] = t;
}

function moveBefore(arr, el){
    let ind = arr.indexOf(el);
    if(ind !== -1 && ind !== 0){
        swapInArray(arr, ind, ind - 1);
    }
}

function moveAfter(arr, el){
    let ind = arr.indexOf(el);
    if(ind !== -1 && ind !== arr.length - 1){
        swapInArray(arr, ind + 1, ind);
    }
}

// dom methods
function swapInDom(parentNode, i1, i2){
    parentNode.insertBefore(parentNode.children[i1], parentNode.children[i2]);
}

function getDomIndex(el){
    for (let ii = 0; ii < el.parentNode.children.length; ii++){
        if(el.parentNode.children[ii] === el){
            return ii;
        }
    }
}

function moveForward(el){
    let ind = getDomIndex(el);
    if(ind !== -1 && ind !== 0){
        swapInDom(el.parentNode, ind, ind - 1);
    }
}

function moveBackward(el){
    let ind = getDomIndex(el);
    if(ind !== -1 && ind !== el.parentNode.children.length - 1){
        swapInDom(el.parentNode, ind + 1, ind);
    }
}
Weilory
  • 1,807
  • 9
  • 24
0

If you are not allowed to use in-place swap for some reason, here is a solution with map:

function swapElements(array, source, dest) {
  return source === dest
? array : array.map((item, index) => index === source
  ? array[dest] : index === dest 
  ? array[source] : item);
}

const arr = ['a', 'b', 'c'];
const s1 = swapElements(arr, 0, 1);
console.log(s1[0] === 'b');
console.log(s1[1] === 'a');

const s2 = swapElements(arr, 2, 0);
console.log(s2[0] === 'c');
console.log(s2[2] === 'a');

Here is typescript code for quick copy-pasting:

function swapElements(array: Array<any>, source: number, dest: number) {
  return source === dest
    ? array : array.map((item, index) => index === source
      ? array[dest] : index === dest 
      ? array[source] : item);
}
snnsnn
  • 5,654
  • 1
  • 30
  • 36
-1

Just for the fun of it, another way without using any extra variable would be:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

// swap index 0 and 2
arr[arr.length] = arr[0];   // copy idx1 to the end of the array
arr[0] = arr[2];            // copy idx2 to idx1
arr[2] = arr[arr.length-1]; // copy idx1 to idx2
arr.length--;               // remove idx1 (was added to the end of the array)


console.log( arr ); // -> [3, 2, 1, 4, 5, 6, 7, 8, 9]
vsync
  • 103,437
  • 51
  • 275
  • 359
-1

try this function...

$(document).ready(function () {
        var pair = [];
        var destinationarray = ['AAA','BBB','CCC'];

        var cityItems = getCityList(destinationarray);
        for (var i = 0; i < cityItems.length; i++) {
            pair = [];
            var ending_point = "";
            for (var j = 0; j < cityItems[i].length; j++) {
                pair.push(cityItems[i][j]);
            }
            alert(pair);
            console.log(pair)
        }

    });
    function getCityList(inputArray) {
        var Util = function () {
        };

        Util.getPermuts = function (array, start, output) {
            if (start >= array.length) {
                var arr = array.slice(0);
                output.push(arr);
            } else {
                var i;

                for (i = start; i < array.length; ++i) {
                    Util.swap(array, start, i);
                    Util.getPermuts(array, start + 1, output);
                    Util.swap(array, start, i);
                }
            }
        }

        Util.getAllPossiblePermuts = function (array, output) {
            Util.getPermuts(array, 0, output);
        }

        Util.swap = function (array, from, to) {
            var tmp = array[from];
            array[from] = array[to];
            array[to] = tmp;
        }
        var output = [];
        Util.getAllPossiblePermuts(inputArray, output);
        return output;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
-1

Using ES6 it's possible to do it like this...

Imagine you have these 2 arrays...

const a = ["a", "b", "c", "d", "e"];
const b = [5, 4, 3, 2, 1];

and you want to swap the first values:

const [a0] = a;
a[0] = b[0];
b[0] = a0;

and value:

a; //[5, "b", "c", "d", "e"]
b; //["a", 4, 3, 2, 1]
Alireza
  • 93,149
  • 25
  • 259
  • 162
-3

If need swap first and last elements only:

array.unshift( array.pop() );
  • This code is flawed. It takes the last element of the array then puts it at the beginning, that isn't swapping. This code does this: `[1, 2, 3] => [3, 1, 2]` instead of `[1, 2, 3] => [3, 2, 1]`. – David Archibald Dec 19 '16 at 04:27