Brian McGinity
Brian McGinity

Reputation: 5935

Associate Array splice does not work

I am trying to understand why in nodejs array splice does not work on an associate array.

var a = [];

a['x1'] = 234234;
a['x2'] = 565464;

console.log("Init-------");
showIt();

a.splice(0, 1);
console.log("After splice-------");
showIt();

delete a['x1'];
console.log("After delete-------");
showIt();

function showIt(){
    var keys = Object.keys(a);
    var len  = keys.length;
    var i=0;
    while (i < len) {
        console.log( '    ' + i +  ' ------------ ' + keys[i] );
        i++;
    }
}

Results:

Init-------
        0 ------------ x1
        1 ------------ x2
After splice-------
        0 ------------ x1
        1 ------------ x2
After delete-------
        0 ------------ x2

Splicing the array does nothing...

Same results in a browser...

Update:

Splice works as expected when the array is defined as:

var a = ['x1','x2','x3'];
console.log("Init-------");
console.log(a);

a.splice('x1', 1);
console.log("After splice-------");
console.log(a);

Looks like in the first example, the array is being treated as if is was defined as a object {} in the 2nd, it's being treated more like an array.

To the Moderators:

This is not really a question about spare arrays, it is more of a question of an array which is starting at 0 and growing sequentially to 10 million over a period of days. As it is growing the array is being deleted from so that around 1000 items are in the array at one time.

I am considering forcing the use of hash tables by using non-numeric keys or defining as a object {} so that the it acts like a sparse array.

In the end, I am not sure if it matters...

Upvotes: 1

Views: 2124

Answers (1)

rvighne
rvighne

Reputation: 21897

In JavaScript there is no such thing as an associative array -- there are arrays (like normal arrays in other languages) and objects (like assoc. arrays in other languages). In your example a is a normal array but you set non-numerical keys on it, so the normal array methods (like splice) do not see it. They only look in the range 0...a.length.

Making a an object won't help; it is not possible to splice an object. Try using only numerical keys ([1] instead of ['x1']).

Upvotes: 1

Related Questions