Maybe I have just been searching on the wrong keywords, but I have been trying to find an example of a JavaScript (preferably ES2015+) function to swap two array values in a non-mutating (immutable) way. I'd also like to do this using pure JS and not have to add in a immutability library.
For example, if I have [1, 2, 3, 4, 5, 6]
, I'd like to pass 3 and 4 (or probably their indexes) into a function that returns a new array [1, 2, 4, 3, 5, 6]
. I found a few ways to do this, but they mutate the array by directly replacing the values. I need an immutable way. I am guessing maybe using slice? I am doing this is a React component if that matters and the array is a state value.
TIA!
slice
) and then swap them.firstIndex
andsecondIndex
, and it also drops the last element.