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.
As @thefourtheye already mentioned it is better to use .filter
for your example.
However, if you want to remove an element by index using spread operator you can do the following:
let arrayOld = ['apple', 'orange', 'fig']
let index = 1;
let arrayNew = [...arrayOld.slice(0, index), ...arrayOld.slice(index + 1)];
console.log(arrayOld);
console.log(arrayNew);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With