How to remove a specified item from the object array in JavaScript?
In JavaScript, there is no obvious method for removing elements from an array. There is a pop() function that exists but it only removes items from the end of an array. The old but gold splice method can remove items from the specified index. We can use it like fruits.splice(itemIndex, 1) to remove an item in that index. But before, we need to find itemIndex like fruits.findIndex(x => x.name === '🍎')
. Therefore we need to execute two functions to remove an item.
So we need to find a simple method that removes an item from the array. We can use the filter function for this:
fruits = fruits.filter(x => x.name != "🍎")
Conclusion
The filter function is the cleanest method compared to other alternatives. Also its an immutable function so it cannot have side effects like splice method. I think its best way to remove an element from the array.
See you in my next post ✌️