How do I remove an object from an array with JavaScript?
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'}]
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.
You can use either the splice()
method or the delete
operator.
The main difference is that when you delete an array element using the delete
operator, the length of the array is not affected, even if you delete the last element of the array. On the other hand, the splice()
method shifts all the elements such that no holes remain in the place of the deleted element.
Example using the delete
operator:
var trees = ["redwood", "bay", "cedar", "oak", "maple"];
delete trees[3];
if (3 in trees) {
// this does not get executed
}
console.log(trees.length); // 5
console.log(trees); // ["redwood", "bay", "cedar", undefined, "maple"]
Example using the splice()
method:
var trees = ["redwood", "bay", "cedar", "oak", "maple"];
trees.splice(3, 1);
console.log(trees.length); // 4
console.log(trees); // ["redwood", "bay", "cedar", "maple"]