I'm trying to swap 2 elements within an array in a functional way in javascript (es6)
let arr = [1,2,3,4,5,6]
let result = swap(arr, 1, 2) // input: array, first element, second element
// result=[1,3,2,4,5,6]
The only way I could think about is:
const swap = (arr, a, b) =>
arr.map( (curr,i) => i === a ? arr[b] : curr )
.map( (curr,i) => i === b ? arr[a] : curr )
But this code runs twice over the array, and not readable at all. Any suggestions for a nice clean functional code?
Thanks.