Skip to content

Instantly share code, notes, and snippets.

@beephotography
Last active October 27, 2019 13:09
Show Gist options
  • Save beephotography/d4ef50dee1e01e7f7a1ca1858d606dac to your computer and use it in GitHub Desktop.
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.
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