Saturday, May 25, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  120] [ 5]  / answers: 1 / hits: 21161  / 11 Years ago, mon, july 15, 2013, 12:00:00

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.


More From » arrays

 Answers
9

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.


[#76986] Sunday, July 14, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
magdalena

Total Points: 364
Total Questions: 101
Total Answers: 92

Location: Namibia
Member since Mon, Nov 14, 2022
2 Years ago
;