I was thinking about simply calling list.reverse().
But then I realised it would work as swap only when list.length = x + y + 1.
For variable number of elements
I have looked into various modern Javascript constructions to this effect, including Map and map, but sadly none has resulted in a code that was more compact or faster than this old-fashioned, loop-based construction:
function multiswap(arr,i0,i1) {/* argument immutable if string */
if (arr.split) return multiswap(arr.split(""), i0, i1).join("");
var diff = [];
for (let i in i0) diff[i0[i]] = arr[i1[i]];
return Object.assign(arr,diff);
}
Example:
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var [x,y,z] = [14,6,15];
var output = document.getElementsByTagName("code");
output[0].innerHTML = alphabet;
output[1].innerHTML = multiswap(alphabet, [0,25], [25,0]);
output[2].innerHTML = multiswap(alphabet, [0,25,z,1,y,x], [25,0,x,y,z,3]);
If you want a single expression, using native javascript,
remember that the return value from a splice operation
contains the element(s) that was removed.
The [0] is necessary at the end of the expression as Array.splice() returns an array, and in this situation we require the single element in the returned array.
For two or more elements (fixed number)
No temporary variable required!
I was thinking about simply calling
list.reverse()
.But then I realised it would work as swap only when
list.length = x + y + 1
.For variable number of elements
I have looked into various modern Javascript constructions to this effect, including Map and map, but sadly none has resulted in a code that was more compact or faster than this old-fashioned, loop-based construction:
Here's a compact version swaps value at i1 with i2 in arr
You only need one temporary variable.
If you don't want to use temp variable in ES5, this is one way to swap array elements.
If you want a single expression, using native javascript, remember that the return value from a splice operation contains the element(s) that was removed.
Edit:
The
[0]
is necessary at the end of the expression asArray.splice()
returns an array, and in this situation we require the single element in the returned array.