Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element from array, using slice

Tags:

I am trying to remove a element from my array using slice, but i can't get it to work, look at this piece of code.

    console.log(this.activeEffects); // Prints my array
    console.log(this.activeEffects.slice(0,1)); // Remove from index 0, and remove one.
    console.log(this.activeEffects); // Prints array again, this time my element should be gone

Result of this is.

enter image description here

So what is get from this is, at first the array is whole, as it should be. Then its prints what is sliced of the array. Finally the third should be empty? or?

like image 697
MartinElvar Avatar asked Aug 07 '12 14:08

MartinElvar


People also ask

How do you remove an element from a slice?

To remove element from array using slice with JavaScript, we can get the index of the element we want to remove, then we can call slice and use the spread operator to create a new array without the element we remove. We have items. slice(0, index) to return an items array items from index 0 to index - 1 .

How do I remove a specific element from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do you slice an element from an array?

The slice() method returns selected elements in an array, as a new array. The slice() method selects from a given start, up to a (not inclusive) given end. The slice() method does not change the original array.


2 Answers

function removeItemWithSlice(index) {   return [...items.slice(0, index), ...items.slice(index + 1)] } 

Slice will create a new array. We create two arrays: from beggining to index and from index+1 to end. Then we apply the spread operator (...) to take the items of those arrays and create a new single array containing all the items we care. I will paste an equivalent way if you don't like the one liner:

function removeItemWithSlice(index) {   const firstArr = items.slice(0, index);   const secondArr = items.slice(index + 1);   return [...firstArr , ...secondArr] } 
like image 71
corlaez Avatar answered Sep 19 '22 17:09

corlaez


I believe you're looking for splice. From W3 Schools:

The splice() method adds/removes items to/from an array, and returns the removed item(s).

Take a look at the example on that page; the use case there is similar to what you want to achieve.

EDIT: Alternative link to MDN, as suggested by Nicosunshine; much more information about the command there.

like image 22
TSL Avatar answered Sep 22 '22 17:09

TSL