46

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?

1

3 Answers 3

124

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
Sign up to request clarification or add additional context in comments.

3 Comments

Nice!! How come no one else has voted this answer up.
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];
88

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

2 Comments

O(1) which below is not
without mutation: const swapArrayElements = (arr, a, b) => { let _arr = [...arr]; let temp = _arr[a]; _arr[a] = _arr[b]; _arr[b] = temp; return _arr }
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.