45

Possible Duplicate:
Javascript swap array elements

I have a array like this:

this.myArray = [0,1,2,3,4,5,6,7,8,9];

Now what I want to do is, swap positions of two items give their positions. For example, i want to swap item 4 (which is 3) with item 8 (which is 7) Which should result in:

this.myArray = [0,1,2,7,4,5,6,3,8,9];

How can I achieve this?

Community
  • 1
  • 1
ssdesign
  • 2,743
  • 6
  • 37
  • 53
  • 2
    Duplicate (with some outrageous solutions for your amusement) - http://stackoverflow.com/questions/872310/javascript-swap-array-elements – Chetan S Oct 25 '10 at 03:01

3 Answers3

123

The return value from a splice is the element(s) that was removed-

no need of a temp variable

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

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

alert(arr.swapItems(3, 7));

returned value: (Array)

    0,1,2,7,4,5,6,3,8,9
kennebec
  • 102,654
  • 32
  • 106
  • 127
  • 1
    Nice!! How come no one else has voted this answer up. – zachzurn Nov 22 '11 at 08:02
  • The key for understanding that solution is that splice() can have additional items after start and deleteCount which will get inserted at the splicing position. Only one blemish: splice() returns an array, so to get the one (and only) element from that array, one would have to say: `this[a]= this.splice(b, 1, this[a])[0];` – trembl Dec 08 '11 at 07:11
  • 19
    Consider this as well, splice is O(n), http://stackoverflow.com/questions/11514308/big-o-of-javascript-arrays – Nick Apr 05 '14 at 18:33
85

Just reassign the elements, creating an intermediate variable to save the first one you over-write:

var swapArrayElements = function(arr, indexA, indexB) {
  var temp = arr[indexA];
  arr[indexA] = arr[indexB];
  arr[indexB] = temp;
};
// You would use this like: swapArrayElements(myArray, 3, 7);

If you want to make this easier to use, you can even add this to the builtin Array prototype (as kennebec@ suggests); however, be aware that this is generally a bad pattern to avoid (since this can create issues when multiple different libraries have different ideas of what belongs in the builtin types):

Array.prototype.swap = function(indexA, indexB) {
   swapArrayElements(this, indexA, indexB);
};
// You would use this like myArray.swap(3, 7);

Note that this solution is significantly more efficient than the alternative using splice(). (O(1) vs O(n)).

Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200
5

You can just use a temp variable to move things around, for example:

var temp = this.myArray[3];
this.myArray[3] = this.myArray[7];
this.myArray[7] = temp;

You can test it out here, or in function form:

Array.prototype.swap = function(a, b) {
  var temp = this[a];
  this[a] = this[b];
  this[b] = temp;
};

Then you'd just call it like this:

this.myArray.swap(3, 7);

You can test that version here.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155