How can I remove all objects from an array based on a property value ?
function removeByKey(array, fieldName){
array.some(function(item, index) {
return (array[index].name === fieldName) ? !!(array.splice(index, 1)) : false;
});
return array;
}
const myarr = [
{
name: 'foo',
school: 'hoo'
},{
name: 'foo',
school: 'xooo'
},{
name: 'bar',
school: 'xooo'
}
];
console.log(removeByKey(myarr, 'foo'))
in the above code, it just removes one of the objects. how can i remove all if matches?
Why not use filter
MDN ?
const myarr = [
{
name: 'foo',
school: 'hoo'
},{
name: 'foo',
school: 'xooo'
},{
name: 'bar',
school: 'xooo'
}
];
const filteredArray = myarr.filter(obj => obj.name !== 'foo');
Example: https://repl.it/repls/SimultaneousSentimentalForms
Edited to match the comment.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments