简体   繁体   中英

removing objects from array

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.

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.

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.

function removeObject(obj, arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] === obj) {
      arr.splice(i, 1);
      break;
    }
  }
}

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]);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM