Home:ALL Converter>Best practice switching place of two items in an array

Best practice switching place of two items in an array

Ask Time:2011-10-26T13:21:50         Author:Mohsen

Json Formatter

What is best practice for switching two items place in an Array via JavaScript?

For example if we have this array ['one', 'two', 'three', 'four', 'five', 'six'] and want to replace two with five to get this final result: ['one', 'five', 'three', 'four', 'two', 'six'].

enter image description here

The ideal solution is short and efficient.

Update:

The var temp trick is working and I know it. My question is: is using JavaScript native Array methods faster or not?

Something like array.splice().concat().blah().blah() seems is faster and use less memory. I didn't develope a function that using Array methods but I'm sure it's possible.

Author:Mohsen,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/7898957/best-practice-switching-place-of-two-items-in-an-array
Guffa :

Just use a variable as temporary storage:\n\nvar temp = data[1];\ndata[1] = data[4];\ndata[4] = temp;\n\n\nAs this just copies values in the array it avoids methods like slice and splice that move around big parts of the array or creates entirely new arrays, which would be very expensive in comparison, and also scales badly. This is an O(1) operation, while splicing would be an O(n) operation where n is the number of items that would be moved, which would be something like length*2-index1-index2.\n\nHere is a performance test for different ways of swapping the items: http://jsperf.com/array-item-swap/2\n\nEven if you use splice in a way so that it would not need to move around a lot of data, it's still slow. Copying the values is about 50 times faster.",
2011-10-26T05:25:42
yy