32

Suppose I have an array of objects called MyArray and that a certain function returns a reference for a particular element within that array; something like this:

MyArray = [Object1, Object2, ..., Objectn];

function DoWork() {

   var TheObject = GetTheObject(SomeParamter);
}

At this point, TheObject points to a certain element in the array. Suppose I want to remove this element from MyArray, is this possible without having to reloop through the array to get the index of the element?

I'm looking for something like splice that would work with the reference to the element rather than the index of the element.

6
  • possible duplicate: stackoverflow.com/questions/3396088/… Commented Jul 15, 2013 at 15:19
  • 1
    Writing TheObject = null will not clear the object from the array. You have it wrong. Commented Jul 15, 2013 at 15:19
  • 2
    arr.splice(arr.indexOf(obj), 1); Commented Jul 15, 2013 at 15:20
  • If an object should be removed form an array, there is no way around that you or the engine loops over the array. What you can think about is to add an optional parameter to GetTheObject that will remove if true or keep if false. Commented Jul 15, 2013 at 15:21
  • @dandavis: you got it Commented Jul 15, 2013 at 15:21

1 Answer 1

54

Simply use Array.prototype.indexOf:

let index = MyArray.indexOf(TheObject);
if(index !== -1) {
  MyArray.splice(index, 1);
}

Keep in mind that if targeting IE < 9 you will need to introduce a polyfill for indexOf; you can find one in the MDN page.

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

10 Comments

where did remove come from?
Ok, then if it doesn't work in IE8 I'll still accept the answer and will keep it in mind for later even though I have to reloop since IE8 support is a must for now.
@frenchie: indexOf reloops in all browsers anyway. I didn't mean to suggest it somehow determined what the index is out of thin air.
This doesn't answer the question. OP asked to remove an element by reference and the answer does not do that, it removes it by index.
@tshm001: Uh, how does multiple arrays make sense in the context of this question, or even any context at all? Speaking about this question, it clearly says "I want to remove this element from MyArray" -- there's no ambiguity there. In a more general context, how would it be possible for any language or library to offer a "remove this object in whatever container it might be in" unless you explicitly code it to search a given set of containers? It makes absolutely no sense.
|

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.