Last active
October 27, 2019 13:09
-
-
Save beephotography/d4ef50dee1e01e7f7a1ca1858d606dac to your computer and use it in GitHub Desktop.
Swaps to elements of an array without mutating the original array. Returns the swapped array.
This file contains hidden or 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
const swapArrayElements = (arr, index1, index2) => arr.map((val, idx) => { | |
if (idx === index1) return arr[index2]; | |
if (idx === index2) return arr[index1]; | |
return val; | |
}); | |
const foo = [1, 2, 3, 4, 5]; | |
const swapped = swapArrayElements(foo, 1, 3); | |
console.log(foo); //=> [1, 2, 3, 4, 5] | |
console.log(swapped); //=> [ 1, 4, 3, 2, 5 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment