Sometimes, we want to remove objects from array by object property with JavaScript.
In this article, we’ll look at how to remove objects from array by object property with JavaScript.
How to remove objects from array by object property with JavaScript?
To remove objects from array by object property with JavaScript, we call array map
with to get the values of the property in each object.
And then we get the index of it with indexOf
and call splice
to remove the item at the given index in the original array.
For instance, we write
const removeIndex = array.map((item) => item.id).indexOf("abc");
array.splice(removeIndex, 1);
to call array.map
to get the value of the id
property in each item
in array
.
Then we get the index of the first item with id
'abc'
with indexOf
.
Next, we call array.splice
with the removeIndex
and 1 to remove the item in array
at removeIndex
in place.
Conclusion
To remove objects from array by object property with JavaScript, we call array map
with to get the values of the property in each object.
And then we get the index of it with indexOf
and call splice
to remove the item at the given index in the original array.