Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an element from an array in JavaScript with slice or spread

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.

like image 443
svnm Avatar asked Jun 14 '16 07:06

svnm


1 Answers

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);
like image 57
Oleksii Aza Avatar answered Nov 15 '22 18:11

Oleksii Aza