views:

111

answers:

3

Hi all,

Is it possible to delete an entry from a JavaScript array? The entry in the list gets replaced with null when delete operator is used.

data = [{pid:30, pname:abc}, {pid:31, pname:def}, {pid:32, pname:zxc}]
delete data[1]

becomes:

data = [{pid:30, pname:abc}, null, {pid:32, pname:zxc}]

FYI I'm getting this as json back from an ajax call. The returned value is parsed like var data = YAHOO.lang.JSON.parse(result.value || '[]')

+1  A: 

There are many librarys out there that deal with the serialization and deserialzation of JSON content. Many of those librarys also allow you to manipulate the data from JSON also.

Depending on what language you're using will determine which library you decide to use.

More details would be helpful.

Jamie Dixon
its javascript and json is returned from an ajax call to php. the returned value is parsed likevar data = YAHOO.lang.JSON.parse(result.value || '[]');
zapping
FYI I updated the question to include the specific JavaScript context the OP is in.
Crescent Fresh
wow thx for that (Y)
zapping
+1  A: 

What about sort()ing and then splice()ing the list?

graphicdivine
thx splice did it. data.splice(1,1).
zapping
Why sort() first?
Roatin Marth
To cellect all the nulls together and splice them all at once.
graphicdivine
A: 

This is a problem with the JavaScript Array class. Deleting a value always leaves a hole. You need to create a new array without the hole. Something like this might be helpful:

    Array.prototype.removeItem = function(index){
        var newArray = []
        for (var i =0; i < this.length; ++i){
            if (i==index||typeof this[i] === "undefined") continue;
            newArray.push(this[i]);
        }
        return newArray;
    }

    var a1 = [1,2,3,4,5]
    delete a1[1]
    alert(a1.join())
    //prints 1,,3,4,5

    var a2 = a1.removeItem(3)
    alert(a2.join())
    //prints 1,3,5 -- removed item 3 and previously "deleted" item 1
Mark Porter