-
-
Save Vladmel1234/035aa74726bf5fec807dff3c82e04369 to your computer and use it in GitHub Desktop.
Swap two array elements (JavaScript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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