i have an array = [] and it contains objects... obj, obj, obj. I have to remove obj two, but i don't know the index... so how can i remove obj. the name of the object is also same.
4 Answers
The ES5 way to do this is with Array.filter
myarray = myarray.filter(function(val, index, a) {
return (val !== obj);
});
See the MDN page linked above for a version to use if you don't have ES5.
Technically this creates a new array, rather than modify the original array. However splice as proposed in other answers isn't particularly efficient anyway since it has to renumber all of the indices above each matching element, and will do so over and over if there's more than one match.
Comments
I hope it helps you:
function removeByElement(array,obj) {
for(var i=0; i<array.length;i++ ) {
if(array[i]==obj) {
array.splice(i,1);
break;
}
}
}
EDIT: breaking the loop.
2 Comments
i++. Either break once you've deleted an item, or traverse the array in reverse order.if you do not know the index, you have to iterate on all elements and check each if they are the one you look for, and then delete it.
var len = your_array.length;
for(var i=0; i<len;i++){
if(typeof(your_arry[i])=='classOfTypeYouLookFor'){// OR if(your_array[i].property_of_class && your_array[i].property_of_class==some_specific_value){
delete(your_arry[i]);
}
}