How do I remove an object from an array with JavaScript? [duplicate]
I have an JavaScript object like this:
id="1";
name = "serdar";
and I have an Array which contains many objects of above. How can I remove an object from that array such as like that:
obj[1].remove();
Solution 1:
Well splice
works:
var arr = [{id:1,name:'serdar'}];
arr.splice(0,1);
// []
Do NOT use the delete
operator on Arrays. delete
will not remove an entry from an Array, it will simply replace it with undefined
.
var arr = [0,1,2];
delete arr[1];
// [0, undefined, 2]
But maybe you want something like this?
var removeByAttr = function(arr, attr, value){
var i = arr.length;
while(i--){
if( arr[i]
&& arr[i].hasOwnProperty(attr)
&& (arguments.length > 2 && arr[i][attr] === value ) ){
arr.splice(i,1);
}
}
return arr;
}
Just an example below.
var arr = [{id:1,name:'serdar'}, {id:2,name:'alfalfa'},{id:3,name:'joe'}];
removeByAttr(arr, 'id', 1);
// [{id:2,name:'alfalfa'}, {id:3,name:'joe'}]
removeByAttr(arr, 'name', 'joe');
// [{id:2,name:'alfalfa'}]
Solution 2:
If you have access to ES2015 functions, and you're looking for a more functional approach I'd go with something like:
const people = [
{ id: 1, name: 'serdar' },
{ id: 5, name: 'alex' },
{ id: 300, name: 'brittany' }
];
const idToRemove = 5;
const filteredPeople = people.filter((item) => item.id !== idToRemove);
// [
// { id: 1, name: 'serdar' },
// { id: 300, name: 'brittany' }
// [
Watch out though, filter()
is non-mutating, so you'll get a new array back.
See the Mozilla Developer Network notes on Filter.
Solution 3:
Cleanest and fastest way (ES6)
const apps = [
{id:1, name:'Jon'},
{id:2, name:'Dave'},
{id:3, name:'Joe'}
]
//remove item with id=2
const itemToBeRemoved = {id:2, name:'Dave'}
apps.splice(apps.findIndex(a => a.id === itemToBeRemoved.id) , 1)
//print result
console.log(apps)
Update: if any chance item doesn't exist in the look up array please use below solution, updated based on MaxZoom's comment
const apps = [
{id:1, name:'Jon'},
{id:3, name:'Joe'}
]
//remove item with id=2
const itemToBeRemoved = {id:2, name:'Dave'}
const findIndex = apps.findIndex(a => a.id === itemToBeRemoved.id)
findIndex !== -1 && apps.splice(findIndex , 1)
//print result
console.log(apps)