159

Can anyone give me a sample/example of JavaScript with a multidimensional array of inputs? Hope you could help because I'm still new to the JavaScript.

Like when you input 2 rows and 2 columns the output of it will be 2 rows of input and 2 columns of input.

Like this:

[input][input]                
[input][input]
Adam
  • 25,960
  • 22
  • 158
  • 247
SpitFire
  • 1,621
  • 2
  • 11
  • 8

15 Answers15

336
var numeric = [
    ['input1','input2'],
    ['input3','input4']
];
numeric[0][0] == 'input1';
numeric[0][1] == 'input2';
numeric[1][0] == 'input3';
numeric[1][1] == 'input4';

var obj = {
    'row1' : {
        'key1' : 'input1',
        'key2' : 'input2'
    },
    'row2' : {
        'key3' : 'input3',
        'key4' : 'input4'
    }
};
obj.row1.key1 == 'input1';
obj.row1.key2 == 'input2';
obj.row2.key1 == 'input3';
obj.row2.key2 == 'input4';

var mixed = {
    'row1' : ['input1', 'inpu2'],
    'row2' : ['input3', 'input4']
};
mixed.row1[0] == 'input1';
mixed.row1[1] == 'input2';
mixed.row2[0] == 'input3';
mixed.row2[1] == 'input4';

http://jsfiddle.net/z4Un3/

And if you're wanting to store DOM elements:

var inputs = [
    [
        document.createElement('input'),
        document.createElement('input')
    ],
    [
        document.createElement('input'),
        document.createElement('input')
    ]
];
inputs[0][0].id = 'input1';
inputs[0][1].id = 'input2';
inputs[1][0].id = 'input3';
inputs[1][1].id = 'input4';

Not real sure how useful the above is until you attach the elements. The below may be more what you're looking for:

<input text="text" id="input5"/>
<input text="text" id="input6"/>
<input text="text" id="input7"/>
<input text="text" id="input8"/>    
var els = [
    [
        document.getElementById('input5'),
        document.getElementById('input6')
    ],
    [
        document.getElementById('input7'),
        document.getElementById('input8')
    ]
];    
els[0][0].id = 'input5';
els[0][1].id = 'input6';
els[1][0].id = 'input7';
els[1][1].id = 'input8';

http://jsfiddle.net/z4Un3/3/

Or, maybe this:

<input text="text" value="4" id="input5"/>
<input text="text" value="4" id="input6"/>
<br/>
<input text="text" value="2" id="input7"/>
<input text="text" value="4" id="input8"/>

var els = [
    [
        document.getElementById('input5'),
        document.getElementById('input6')
    ],
    [
        document.getElementById('input7'),
        document.getElementById('input8')
    ]
];

var result = [];

for (var i = 0; i < els.length; i++) {
    result[result.length] = els[0][i].value - els[1][i].value;
}

Which gives:

[2, 0]

In the console. If you want to output that to text, you can result.join(' ');, which would give you 2 0.

http://jsfiddle.net/z4Un3/6/

EDIT

And a working demonstration:

<input text="text" value="4" id="input5"/>
<input text="text" value="4" id="input6"/>
<br/>
<input text="text" value="2" id="input7"/>
<input text="text" value="4" id="input8"/>
<br/>
<input type="button" value="Add" onclick="add()"/>

// This would just go in a script block in the head
function add() {
    var els = [
        [
            document.getElementById('input5'),
            document.getElementById('input6')
        ],
        [
            document.getElementById('input7'),
            document.getElementById('input8')
        ]
    ];

    var result = [];

    for (var i = 0; i < els.length; i++) {
        result[result.length] = parseInt(els[0][i].value) - parseInt(els[1][i].value);
    }

    alert(result.join(' '));
}

http://jsfiddle.net/z4Un3/8/

user229044
  • 232,980
  • 40
  • 330
  • 338
Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
  • 1
    can i know how thus this work sir.. im kinda confuse of Javascript – SpitFire Sep 25 '11 at 13:21
  • 1
    What is it you're confused about? – Jared Farrish Sep 25 '11 at 13:22
  • about is it like im going to make an HTML file where there is two inputs and it is the inputs of Rows and Columns or something else? – SpitFire Sep 25 '11 at 13:26
  • 1
    I'm not really following what you're saying. What are you trying to with your array? (Also, see my last edit.) – Jared Farrish Sep 25 '11 at 13:30
  • in array im going to input a number of rows and columns with a unique name or ID..and another rows and columns with a unique name or ID where the the first array of inputs rows and columns will be subtracted to the 2nd inputs of R and C.. – SpitFire Sep 25 '11 at 13:34
  • Ok, see my very last edit. Note, you need `console` open to see the result (Chrome, Firefox w/Firebug, IE9). Also, this is running `onDOMReady`; your actual script would need to run at least after the elements were parsed into the DOM, but not before. – Jared Farrish Sep 25 '11 at 13:39
  • Nice answer, but I can see where the OP is coming from. Advanced answer for people who don't yet have an understanding of JS to appreciate the content provided above. – user66001 Feb 07 '14 at 21:00
  • @JaredFarrish Correct me if I'm wrong but if you use the obj syntax or mixed you can still do `obj['Value']` or `var ValueVariable = 'Value'; obj[ValueVariable]` instead of `obj.Value` to get or set values. Right? – Dan Jan 07 '15 at 22:10
  • @Dan - Yes that would work. Any place where a variable will be interpreted as a string in that situation would work. – Jared Farrish Dec 30 '15 at 17:21
30

Quote taken from Data Structures and Algorithms with JavaScript

The Good Parts (O’Reilly, p. 64). Crockford extends the JavaScript array object with a function that sets the number of rows and columns and sets each value to a value passed to the function. Here is his definition:

Array.matrix = function(numrows, numcols, initial) {
    var arr = [];
    for (var i = 0; i < numrows; ++i) {
        var columns = [];
        for (var j = 0; j < numcols; ++j) {
            columns[j] = initial;
        }
        arr[i] = columns;
    }
    return arr;
}

Here is some code to test the definition:

var nums = Array.matrix(5,5,0);
print(nums[1][1]); // displays 0
var names = Array.matrix(3,3,"");
names[1][2] = "Joe";
print(names[1][2]); // display "Joe"

We can also create a two-dimensional array and initialize it to a set of values in one line:

var grades = [[89, 77, 78],[76, 82, 81],[91, 94, 89]];
print(grades[2][2]); // displays 89
Community
  • 1
  • 1
Teoman shipahi
  • 47,454
  • 15
  • 134
  • 158
17

Declared without value assignment.

2 dimensions...

var arrayName = new Array(new Array());

3 dimensions...

var arrayName = new Array(new Array(new Array()));
ShawnS
  • 337
  • 2
  • 5
  • 8
    Both of these examples seem to only produce 1x1 & 1x1x1 arrays (respectively), maybe properly called single dimension nested arrays. As an example `var test=new Array(new Array());test[0][0]='1';test[0][1]='2';test[1][0]='3';` errors with message `Exception: test[1] is undefined` – user66001 Feb 07 '14 at 20:53
  • 2
    This seems wrong. When I try the code I get a 1x1x0 array. http://jsfiddle.net/zU8SB/1/ How has it gotten 13 upvotes? – Randall Cook Mar 02 '14 at 01:06
  • 1
    Insert with ['Array.push'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) – bagz_man Aug 26 '14 at 00:59
14

I know this is ancient but what about...

4x4 example (actually 4x<anything>):

var matrix = [ [],[],[],[] ]

which can filled by:

for (var i=0; i<4; i++) {
   for (var j=0; j<4; j++) {
      matrix[i][j] = i*j;
   }
}
Dan
  • 2,625
  • 7
  • 39
  • 52
Nadav
  • 1,167
  • 2
  • 19
  • 43
  • Perhaps might make it more obvious that nothing "outside" 1x4 (so not matrix[3][3] being the 4th row, 4th column) is declared (i.e., accessible) with this var declaration. Also, the example setting element [0][1] to 5 skips the first element. Using [0][0] instead, could be useful to demonstrate an important point of arrays in a lot of programming languages. – user66001 Feb 07 '14 at 20:57
9

Hope the following code suits your requirement

var row= 20;
var column= 10;
var f = new Array();

for (i=0;i<row;i++) {
 f[i]=new Array();
 for (j=0;j<column;j++) {
  f[i][j]=0;
 }
}
Aibrean
  • 6,297
  • 1
  • 22
  • 38
Nishanth Suresh
  • 101
  • 1
  • 3
  • YES!! Been struggling with this forever! The secret is creating the extra array at the row column (or if iterating through a grid, the height) – NiCk Newman Nov 23 '15 at 07:07
8
function Array2D(x, y)
{
    var array2D = new Array(x);

    for(var i = 0; i < array2D.length; i++)
    {
        array2D[i] = new Array(y);
    }

    return array2D;
}

var myNewArray = Array2D(4, 9);

myNewArray[3][5] = "booger";
Ken Jinks
  • 161
  • 2
  • 1
8

very simple

var states = [,];
states[0,0] = tName; 
states[0,1] = '1';
states[1,0] = tName; 
states[2,1] = '1';

. . .

states[n,0] = tName; 
states[n,1] = '1';
user4839072
  • 107
  • 1
  • 2
  • 1
    This does not seem to work when I test it in the console. It seems that the old values get deleted when I write to say a[0,1] and a[1,1], the second deletes a[0,1]... – Thomas Dignan Jul 25 '15 at 17:14
4
var size = 0;   
 var darray = new Array();
    function createTable(){
        darray[size] = new Array();
        darray[size][0] = $("#chqdate").val();
        darray[size][1]= $("#chqNo").val();
        darray[size][2] = $("#chqNarration").val() ;
        darray[size][3]= $("#chqAmount").val();
        darray[size][4]= $("#chqMode").val();
    }

increase size var after your function.

Gaurav
  • 304
  • 2
  • 6
4

So here's my solution.

A simple example for a 3x3 Array. You can keep chaining this to go deeper

Array(3).fill().map(a => Array(3))

Or the following function will generate any level deep you like

f = arr => {
    let str = 'return ', l = arr.length;
    arr.forEach((v, i) => {
        str += i < l-1 ? `Array(${v}).fill().map(a => ` : `Array(${v}` + ')'.repeat(l);
    });
    return Function(str)();
}
f([4,5,6]) // Generates a 4x5x6 Array

http://www.binaryoverdose.com/2017/02/07/Generating-Multidimensional-Arrays-in-JavaScript/

2

you can create array follow the code below:

var arraymultidimensional = []
    arraymultidimensional = [[value1,value2],[value3,value4],[value5,value6]];

Result:
[v1][v2] position 0
[v3][v4] position 1
[v5][v6] position 2

For add to array dinamically, use the method below:

//vectorvalue format = "[value,value,...]"
function addToArray(vectorvalue){
  arraymultidimensional[arraymultidimensional.length] = vectorvalue;
}

Hope this helps. :)

b1c10
  • 163
  • 1
  • 6
1

I've created an npm module to do this with some added flexibility:

// create a 3x3 array
var twodimensional = new MultiDimensional([3, 3])

// create a 3x3x4 array
var threedimensional = new MultiDimensional([3, 3, 4])

// create a 4x3x4x2 array
var fourdimensional = new MultiDimensional([4, 3, 4, 2])

// etc...

You can also initialize the positions with any value:

// create a 3x4 array with all positions set to 0
var twodimensional = new MultiDimensional([3, 4], 0)

// create a 3x3x4 array with all positions set to 'Default String'
var threedimensionalAsStrings = new MultiDimensional([3, 3, 4], 'Default String')

Or more advanced:

// create a 3x3x4 array with all positions set to a unique self-aware objects.
var threedimensional = new MultiDimensional([3, 3, 4], function(position, multidimensional) {
    return {
        mydescription: 'I am a cell at position ' + position.join(),
        myposition: position,
        myparent: multidimensional
    }
})

Get and set values at positions:

// get value
threedimensional.position([2, 2, 2])

// set value
threedimensional.position([2, 2, 2], 'New Value')
Arjun Mehta
  • 2,500
  • 1
  • 24
  • 40
1

Create uninitialized multidimensional array:

function MultiArray(a) {
  if (a.length < 1) throw "Invalid array dimension";
  if (a.length == 1) return Array(a[0]);
  return [...Array(a[0])].map(() => MultiArray(a.slice(1)));
}

Create initialized multidimensional array:

function MultiArrayInit(a, init) {
  if (a.length < 1) throw "Invalid array dimension";
  if (a.length == 1) return Array(a[0]).fill(init);
  return [...Array(a[0])].map(() => MultiArrayInit(a.slice(1), init));
}

Usage:

MultiArray([3,4,5]);  // -> Creates an array of [3][4][5] of empty cells

MultiArrayInit([3,4,5], 1);  // -> Creates an array of [3][4][5] of 1s
Yuriy Ershov
  • 354
  • 2
  • 8
  • 1
    This is a great answer. I think you should push for your MultiArrayInit function to be added to ECMA2023. It is sorely lacking in js. – Frazer Kirkman May 02 '22 at 00:02
1

I came up with

let rows = 5;
let cols = 4;
let defaultValue = 0;

Array(rows).fill([]).map((x) => x = Array(cols).fill(defaultValue));

resulting into

(5) [Array(4), Array(4), Array(4), Array(4), Array(4)]
0: (4) [0, 0, 0, 0]
1: (4) [0, 0, 0, 0]
2: (4) [0, 0, 0, 0]
3: (4) [0, 0, 0, 0]
4: (4) [0, 0, 0, 0]
length: 5
Clemens Tolboom
  • 1,872
  • 18
  • 30
0

I've written a one linear for this:

[1, 3, 1, 4, 1].reduceRight((x, y) => new Array(y).fill().map(() => JSON.parse(JSON.stringify(x))), 0);

I feel however I can spend more time to make a JSON.parse(JSON.stringify())-free version which is used for cloning here.

Btw, have a look at my another answer here.

Ebrahim Byagowi
  • 10,338
  • 4
  • 70
  • 81
0

I know this is an old question but here is something to try: Make your multidimensional array, and place it inside an html tag. This way you can precisely aim your array'd input:

//Your Holding tag for your inputs!
<div id='input-container' class='funky'></div>

<script>
    //With VAR: you can seperate each variable with a comma instead of:
    //creating var at the beginning and a semicolon at the end.
    //Creates a cleaner layout of your variables
    var
        arr=[['input1-1','input1-2'],['input2-1','input2-2']],
        //globall calls these letters var so you dont have to recreate variable below
        i,j
    ;

    //Instead of the general 'i<array.length' you can go even further
    //by creating array[i] in place of 'i<array.length'
    for(i=0;arr[i];i++){
    for(j=0;arr[i][j];j++){
        document.getElementById('input-container').innerHTML+=
            "<input class='inner-funky'>"+arr[i][j]+"</input>"
        ;
    }}
</script>

Its simply a neater way to write your code and easier to invoke. You can check my demo here!

Gareth Compton
  • 159
  • 1
  • 12