Skip to content

Instantly share code, notes, and snippets.

@Vladmel1234
Forked from eerohele/swaparrayelements.js
Created June 12, 2017 06:31
Show Gist options
  • Save Vladmel1234/035aa74726bf5fec807dff3c82e04369 to your computer and use it in GitHub Desktop.
Save Vladmel1234/035aa74726bf5fec807dff3c82e04369 to your computer and use it in GitHub Desktop.
Swap two array elements (JavaScript)
/**
* Swap the elements in an array at indexes x and y.
*
* @param (a) The array.
* @param (x) The index of the first element to swap.
* @param (y) The index of the second element to swap.
* @return {Array} A new array with the elements swapped.
*/
var swapArrayElements = function (a, x, y) {
if (a.length === 1) return a;
a.splice(y, 1, a.splice(x, 1, a[y])[0]);
return a;
};
swapArrayElements([1, 2, 3, 4, 5], 1, 3); //=> [ 1, 4, 3, 2, 5 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment