0

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);
3
  • @RoyiNamir Both your examples are arrays of references to objects. In the first case the references are hidden, but they still exist. var a = {}; var b = a; is there a difference between a and b? Is a an object and b a reference to an object? A: No, they are both references to an object. Commented Dec 3, 2013 at 11:36
  • @Tibos you didn;t understand me. I thought he has var g=[{a:1},{b:2}];var myObj={a:1}....and now he needs to find myObj Commented Dec 3, 2013 at 11:37
  • 1
    @RoyiNamir I see. Well he did say "a reference to an object from this array". Anyway, glad to have cleared the misunderstanding :). Commented Dec 3, 2013 at 11:42

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

7 Comments

@RoyiNamir this line arr.splice(arr.indexOf(myObj),1); does the same thing as list.Remove(element); just different syntax
Does indexOf compare objects by reference (just to double-check)?
@RoyiNamir The original code and the version i edited now are entirely equivalent. I did update it to be word-for-word identical to what the OP described. As for IE9+, indeed, but a shim for indexOf can be found in many places, including MDN
@MaximEliseev it compares by strict equality which in case of objects means comparison by reference.
This question can not be answred. there are missing details.
|
0

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.

Comments

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.