views:

73

answers:

3

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?

+2  A: 

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
Didn't know about jsfiddle. Thanks!
Collin
+2  A: 
function swapArrayElements(array_object, index_a, index_b) {
    var temp = array_object[index_a];
    array_object[index_a] = array_object[index_b];
    array_object[index_b] = temp;
 }
Michael Aaron Safyan
A: 

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]);
    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