ES2015 non-mutating array in a React component (or flow action)

Maybe I was just looking for the wrong keywords, but I was trying to find an example of a JavaScript function (preferably ES2015 +) to replace two array values ​​in a non-mutating (immutable) way. I would also like to do this with pure JS and not add immutability to the library.

For example, if I have [1, 2, 3, 4, 5, 6] , I would like to pass 3 and 4 (or, possibly, their indices) to a function that returns a new array [1, 2, 4, 3, 5, 6] . I found several ways to do this, but they mutate the array, directly replacing the values. I need an immutable path. I guess, possibly using a slice? I do this React component if it matters, and the array is a state value.

TIA!

+5
source share
2 answers

Not ES6 (still learning it)

 function swap(array, first, second){ var final = array.slice(); temp = final[first]; final[first] = final[second]; final[second] = temp; return final } 

ES6 Thanks @Benjamin

 const swapIndices = (array,index1,index2) => { const newArray = array.slice(); newArray[index1] = array[index2]; newArray[index2] = array[index1]; return newArray; } 
+6
source
 function swap(arr, i1, i2) { // i1 must be lower if (i1 > i2) i1 = [i2, i2 = i1][0]; return arr .slice(0,i1) .concat(arr[i2]) .concat(arr.slice(i1+1,i2)) .concat(arr[i1]) .concat(arr.slice(i2+1)) } 

Maybe not perfect, but stepping :)

+1
source

Source: https://habr.com/ru/post/1246469/


All Articles