Sometimes, we want to remove element from array using slice with JavaScript.
In this article, we’ll look at how to remove element from array using slice with JavaScript.
How to remove element from array using slice with JavaScript?
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.
For instance, we write:
const items = ['foo', 'bar', 'baz', 'qux']
const index = 1
const arr = [...items.slice(0, index), ...items.slice(index + 1)]
console.log(arr)
We have items.slice(0, index)
to return an items
array items from index 0 to index - 1
.
And we have items.slice(index + 1)
to return the items
array from index index + 1
to the end of the array.
Next, we spread both arrays into a new array and assign it to arr
.
Therefore, arr
is ['foo', 'baz', 'qux']
.
Conclusion
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.