Skip to content

Instantly share code, notes, and snippets.

@aqwert
Created June 8, 2017 04:40
Show Gist options
  • Save aqwert/9804906990c72389ec84b66b20d3d0bf to your computer and use it in GitHub Desktop.
Save aqwert/9804906990c72389ec84b66b20d3d0bf to your computer and use it in GitHub Desktop.
Javascript immutable array manipulation
//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