DeLe
DeLe

Reputation: 2480

JavaScript - control two-dimensional dynamic array

i want to init a two-dimensional dynamic array in javascript, it don't limit element (maybe) like

var dynamic = new Array ();
dynamic[] = new Array ();


after i want to add value to special array like

dynamic[id].push(2); // id = 3, dynamic[3][0] = 2
...
dynamic[id].push(3); // id = 3, dynamic[3][1] = 3
...
dynamic[id].push(5); // id = 5, dynamic[5][0] = 5

it's possible? How can i do that, thanks

Upvotes: 7

Views: 2613

Answers (2)

NickSlash
NickSlash

Reputation: 5077

Overwriting push might not be the best plan. Adding another method/function would make it simpler to understand. Someone reading push(1,3) might assume you're pushing 1 and 3 onto an array instead of 3 into item 1.

var dynamic = [];

dynamic.item = function(index) {
    if (!dynamic[index]) {
        dynamic[index] = [];
    }
    return dynamic[index];
}

this will allow you to do the following:

dynamic.item(1).push(1)

if the "item" does not exist, it is created before its returned, and this allows you to use all array methods on both dimensions of your array. (i beleive)

You could also make this slightly more generic by adding it to the Array prototype which would let you use it on all arrays.

Array.prototype.item = function(index) {
    if (!this[index]) {
        this[index] = init;
    }
    return this[index];
}

Upvotes: 0

Ingo Bürk
Ingo Bürk

Reputation: 20043

One thing you could do is something like this (jsfiddle):

var dynamic = [];

dynamic.push = function (id, value) {
    if (!this[id]) {
        this[id] = [];
    }

    this[id].push(value);
}

dynamic.push(3, 2);
dynamic.push(3, 3);
dynamic.push(5, 5);

Of course, this can be done even better, but it gets the point across. Personally, I'd write a class for this.

Edit: Also, keep in mind that this creates an array with a high potential of having a whole lot of undefined values, which needs to be taken care of when reading from it. Also, arrays with holes like this have bad performance (if this will be an issue -- for a few, even a few hundred, values, it won't matter).

Upvotes: 5

Related Questions