Created
June 8, 2017 04:40
-
-
Save aqwert/9804906990c72389ec84b66b20d3d0bf to your computer and use it in GitHub Desktop.
Javascript immutable array manipulation
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
//Adding to an array without mutating the original | |
return list.concat(item); | |
//--------------------------------------------------------- | |
//Deleting an item in an array without mutating the original | |
return list | |
.slice(0, index) | |
.concat(list.slice(index + 1)); | |
//or in ES6 | |
return [ | |
...list.slice(0, index), | |
...list.slice(index + 1) | |
]; | |
//--------------------------------------------------------- | |
//Updating an item in an array without mutating the original | |
return list | |
.slice(0, index) | |
.concat([list[index] + 1] //in this case increment by one but replace with more complex structure | |
.concat(list.slice(index + 1)); | |
//or in ES6 | |
return [ | |
...list.slice(0, index), | |
list[index] + 1, //in this case increment by one but replace with more complex structure | |
...list.slice(index + 1) | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment