3

I have a javascript object as follow:

obj = {
   a: 'a',
   b: 'b',
}

I add obj to an array as follow:

arr = [];
arr.push(obj);

Now I want to delete arr[0]. I only access to obj, but I want to delete obj then delete automatically arr[0].

How can I do it, Or Is it possible?

Morteza Malvandi
  • 1,144
  • 2
  • 22
  • 59

3 Answers3

1

Save the index at which your object was inserted:

arr.push(obj);
var index = arr.length - 1;

and then add a method to the object to remove it from the array, using the saved index:

obj.remove = function () {
    delete arr[index];
};

Then, somewhere else in your code where arr has gone out of scope, just do

obj.remove();

Note: this will leave a hole in your array at the place where your object was, it will not reorganize the array, shifting elements left and right to fill the hole. If you don't want to leave a hole, do not use an array, instead use a linked list.

jrsala
  • 1,799
  • 11
  • 11
1

You could attach the list to the object itself, then access the list that way in order to delete the object? This is a bit messy, ideally you'd find a way to reorganise your code, but hey these things happen! so this might help:

http://jsfiddle.net/dk79mb3x/1/

// This function, and returning the obj, is not strictly 
// necessary. I am doing it to achieve a state where the obj is 
// in scope, but the list is not.
function defineStuff() {
    var list = [];
    var obj = {
        a: 'a',
        b: 'b',
        // These two are the useful bits!
        container: list,
        index: list.length

        // We can only delete this once, if you try a second time, the
        // index will be incorrect!
        deleted: false;
    };
    list.push(obj);
    return obj;
}

obj = defineStuff();

// Note that the list is no longer in scope
console.log(typeof list);

// But we know it has one item in it... this should log '1'
console.log(obj.container.length);

// Now we can delete via the object like this...
if (!obj.deleted)
    obj.container.splice(obj.index, 1);
// (You could work around this index issue and remove the .deleted flag by
// instead searching the list for something that matches the object. If you
// have an object.key, for example, that would work well.)

// Is it now empty? This should log '0'
console.log(obj.container.length);
sifriday
  • 4,029
  • 1
  • 9
  • 22
0

It's not possible. You must access to arr and then use delete arr[0].

Morteza Malvandi
  • 1,144
  • 2
  • 22
  • 59