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?
How to move an element of an array to a specific position (swap)? Create a temp variable and assign the value of the original position to it. Now, assign the value in the new position to original position. Finally, assign the value in the temp to the new position.
Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable.
Destructuring works great if you want to access object properties and array items. On top of the basic usage, array destructuring is convinient to swap variables, access array items, perform some immutable operations.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With