var listToDelete = ['abc', 'efg'];
var arrayOfObjects = [{id:'abc',name:'oh'}, // delete me
{id:'efg',name:'em'}, // delete me
{id:'hij',name:'ge'}] // all that should remain
How do I remove an object from the array by matching object property?
Only native JavaScript please.
I am having trouble using splice because length diminishes with each deletion. Using clone and splicing on orignal index still leaves you with the problem of diminishing length.
If you just want to remove it from the existing array and not create a new one, try:
As an alternative, more "functional" solution, working on ECMAScript 5, you could use:
According to the definition of 'Array.prototype.reduceRight' in ECMA-262:
So this is a valid usage of
reduceRight
.With lodash/underscore:
If you want to modify the existing array itself, then we have to use splice. Here is the little better/readable way using findWhere of underscore/lodash:
With ES5 or higher
(without lodash/underscore)
With ES5 onwards we have
findIndex
method on array, so its easy without lodash/underscore(ES5 is supported in almost all morden browsers)
About findIndex
as per your answer will be like this. when you click some particular object send the index in the param for the delete me function. This simple code will work like charm.
with filter & indexOf
with filter & includes
If you like short and self descriptive parameters or if you don't want to use
splice
and go with a straight forward filter or if you are simply a SQL person like me:And a sample usage: