1

For example, in

function swap ( arr, i1, i2 ) 
{
    // swaps elements at index i1 and i2
    // in the array arr
    var temp = arr[i1];
    arr[i1] = arr[i2];
    arr[i2] = temp;
}

function reverse_array ( arr ) 
{
    // reverse the order of the elements in array arr
    var i1 = 0, i2 = arr.length;
    while ( i1 != i2 && i1 != --i2 ) swap(arr,i1++,i2);
}

var myArray = [1, 2, 3, 4];
reverse_array(myArray);
myArray.forEach(function(elem) { $('#mydiv').append(elem + ' ') });

the only way I know of implementing a swap function for elements of an array is to pass in the array in. However, that seems inefficient. There must a way of implementing a straight-up swap function for variables of any type. I guess my question really boils down to:

What is the most efficient way of implementing a swap function in JavaScript???

Is there a way of "boxing" (to use a C# term) to variables before passing them into a classic function swap ( a, b ) { temp = a; a = b; b = temp; } procedure?

  • At least the `reverse_array` function is already built in with `Array.reverse()` ? – adeneo Oct 20 '15 at 21:56
  • @adeneo I know, but I'm practicing for job interview, code golf skills, etc. – Spaghetti Coder Oct 20 '15 at 21:57
  • The swap seems okay to me, I don't think there is any better way of doing that in JS. Reversing the array could probably be done in many ways, something like this comes to mind -> http://jsfiddle.net/gx1rfern/ but it's probably slower. – adeneo Oct 20 '15 at 22:08
  • "*However, that seems inefficient*". How? All that is passed is a reference. – RobG Oct 20 '15 at 22:33
  • 1
    Probably a duplicate of [*Javascript swap array elements*](http://stackoverflow.com/questions/872310/javascript-swap-array-elements). – RobG Oct 20 '15 at 22:57

1 Answers1

2

If you use ECMAScript6 you can use destructuring to swap.

var a = 0;
var b = 1;
[a, b] = [b, a];

Which is very handy and one of the reasons I love Javascript.

But check for compatability before you use it. Otherwise you have to use a temp var.

You can reverse an array with the method.

var arr = [1,2,3,4,5,6,7];
arr.reverse(); // [7,6,5,4,3,2,1]

Also passing an array is not inefficient. All you do is pass a reference to the array, and is more efficient than passing two elements from the array.

All variables are identified internally via a reference, the size of the array or object has no effect on code speed when you pass the reference to functions.

Blindman67
  • 51,134
  • 11
  • 73
  • 136