4

So I just discovered today that doing this:

a = { b: { c: 1, d: 2 }, d: {} }
sub = a.b
// sub is { c: 1, d: 2 }

sub is now actually the object stored in a, not a clone.

Now if I do this:

sub.c = "x"
// a is now: { b: { c: 'x', d: 2 }, d: {} } // nice

The same thing applies to arrays.

So I have this array:

arr = [{a: 1, b: 2}, {c: 3, d: 4}]
sub = arr[1]

I'd like to remove sub from array so that arr becomes: [{a: 1, b: 2}] but if I do sub = null I simply assign a new value to sub. Same thing for delete.

delete sub // will unset the sub variable, not the object that it references.

So the question is: how do I remove {c: 3, d: 4} from the array by using sub

Even though it works, I can't use delete arr[1] because I don't know the index. I'm storing the object using the min function of lodash

2
  • 2
    You can't. arr[1] and sub are both references to the same object, but sub is not pointer to the array itself. Commented Oct 9, 2014 at 13:51
  • Please note that there is a big difference between sub.c = "x" and sub = null. In the first case you are reading the value of sub and mutate the object, in the second you are writing a new value to sub. Commented Oct 9, 2014 at 14:17

2 Answers 2

3

To delete element from array, be it primitive value or object, you still use splice. To find element index you would use indexOf. It possible because:

indexOf compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).

So combined together

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

Take a look at this demo:

var arr = [{a: 1, b: 2}, {c: 3, d: 4}]
var sub = arr[1];

alert('Before: ' + JSON.stringify(arr));

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

alert('After: ' + JSON.stringify(arr));

Sign up to request clarification or add additional context in comments.

Comments

2

So the question is: how do I remove {c: 3, d: 4} from the array by using sub

There is no way to do that directly.

Relationships in JavaScript are one-way.

sub is a reference to an object. arr[1] is a reference to the same object.

There is no direct way to get from the object to sub or to arr[1].

Since you know arr contains a reference to the object, you can search for a copy of that reference using indexOf.

var index = arr.indexOf(sub);

You can then use it to remove the element from the array.

arr.splice(index, 1);

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.