Removing an Element by id in JavaScript
Let the variable arr contain
an array of objects:
let arr = [
{
id: 'GYi9GauC4gBF1e2SixDvu',
prop1: 'value11',
prop2: 'value12',
prop3: 'value13',
},
{
id: 'IWSpfBPSV3SXgRF87uO74',
prop1: 'value21',
prop2: 'value22',
prop3: 'value23',
},
{
id: 'JAmjRlfQT8rLTm5tG2m1L',
prop1: 'value31',
prop2: 'value32',
prop3: 'value33',
},
];
Let the variable contain the id of the array
element:
let id = 'IWSpfBPSV3SXgRF87uO74';
Let's remove the element with this id.
Let's use the filter method for this:
let res = arr.filter(elem => {
if (elem.id !== id) {
return elem;
}
});
The code can be simplified:
let res = arr.filter(elem => elem.id !== id);
Let the variable contain the id of the element.
Make a button that will remove the element
with the given id.