Remove element from array, using slice

.slice does not mutate the array, you could use .splice() to remove the item at index i in the array:

this.activeEffects.splice(i, 1)

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]
}

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.


a.slice(0, index).concat(a.slice(index + 1))

Tags:

Javascript