Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove object from array with just the object's reference

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.

like image 970
frenchie Avatar asked Jul 15 '13 15:07

frenchie


People also ask

How can I remove a specific item from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do you remove an object from an array by value?

To remove an object from an array by its value:Call the findIndex() method to get the index of the object in the array. Use the splice() method to remove the element at that index. The splice method changes the contents of the array by removing or replacing existing elements.

How do you remove an object from an array in C++?

There is no built-in way to remove an element from a C++ array. Arrays always have fixed size, so you can't add or remove elements. You do have some other options. For example, you could use the std::vector type, which acts like an array but lets you add and remove elements.


1 Answers

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.

like image 111
Jon Avatar answered Oct 14 '22 05:10

Jon