Maxim Eliseev
Maxim Eliseev

Reputation: 3504

How to delete an object from array by reference (javascript)?

Simple question, but I cannot find a solution.

I have an array of objects. I also have a reference to an object from this array.

I want to delete the object from the array.

How to do it in Javascript (without comparing object properties)?

PS It is easy to do it in C# (using List collection)

 List<SomeObject> list = ........ ;
 SomeObject element =  ......... ;
 list.Remove(element);

Upvotes: 0

Views: 313

Answers (2)

luke1985
luke1985

Reputation: 2354

There is no way to do this with arrays directly. You will have to find or roll your own implementation of an collection which supports similar operation.

Upvotes: 0

Tibos
Tibos

Reputation: 27833

You can use indexOf to get the index of the object and splice to remove it from the array:

var arr = [ { name: 0}, { name : 1 } , {name : 2 } ];
var myObj = arr[1];

arr.splice(arr.indexOf(myObj),1);

console.log(arr);

Upvotes: 3

Related Questions