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?
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
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)).
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.
精彩评论