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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With