I have been watching the video on redux from Dan Abramov avoiding-array-mutations and I have worked out how to use slice
to remove an element from an array by id, returning the new array without mutation.
var arrayOld = ['apple', 'orange', 'fig']
var index = arrayOld.indexOf('orange')
var arrayNew = arrayOld.slice(0,index).concat(arrayOld.slice(index + 1))
// ['apple', 'fig']
I was wondering how I would do the same using es6 spread
syntax?
Also I am wondering why there is not a simpler way: e.g. a helper function in es6 to do this, something that works as simply as the concat method, where you could just pass in the id of the element to remove and it returns the new array, so basically splice but without the mutation.
[...arr]
is the same asarr.slice()
, you could "slice and splice" for no side effects removal[...arrayOld.slice(0,index), ...arrayOld.slice(index+1)]