Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping two items in a javascript array [duplicate]

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?

like image 209
ssdesign Avatar asked Oct 25 '10 02:10

ssdesign


People also ask

How do you swap positions of elements in an array?

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.

How do you duplicate an array in JavaScript?

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.

Can you use array Destructuring to swap elements in an array?

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.


1 Answers

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 
like image 115
kennebec Avatar answered Oct 08 '22 03:10

kennebec