JavaScript - managing a two-dimensional dynamic array

I want to initialize a two-dimensional dynamic array in javascript, it does not limit the element (maybe) like

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


after I want to add a value to a special array, for example

 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 

is it possible? How can i do this thanks

+7
source share
2 answers

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 makes sense. Personally, I would write a class for this.

Edit: Also keep in mind that this creates an array with high potential, with many undefined values โ€‹โ€‹that you need to take care of when reading from it. In addition, arrays with such openings have poor performance (if this is a problem - for several, even several hundred values, it does not matter).

+5
source

Overwriting push might not be the best plan. Adding another method / function would make understanding easier. Someone reading push(1,3) might suggest that you push 1 and 3 on an array instead of 3 on element 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 "element" does not exist, it is created before it is returned, and this allows you to use all array methods in both dimensions of your array. (I believe)

You can also make this a little more general by adding it to the Array prototype, which allows you to use it on all arrays.

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

All Articles