2

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 4

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

oh, and it'll fail if you have two or more consecutive matching elements.
This is a bad approach. If you delete an item, then you'll skip over the next one at i++. Either break once you've deleted an item, or traverse the array in reverse order.
1
function removeObject(obj, arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] === obj) {
      arr.splice(i, 1);
      break;
    }
  }
}

Comments

1

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

2 Comments

This will leave behind a hole in the array
might be I misunderstood the question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.