How to Create Multidimensional Array

How can I create a two dimensional array in JavaScript?

let items = [
[1, 2],
[3, 4],
[5, 6]
];
console.log(items[0][0]); // 1
console.log(items[0][1]); // 2
console.log(items[1][0]); // 3
console.log(items[1][1]); // 4
console.log(items);

How to create multidimensional array

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/

How to define a two-dimensional array?

You're technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this
"list comprehension".

# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5
Matrix = [[0 for x in range(w)] for y in range(h)]

#You can now add items to the list:

Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range...
Matrix[0][6] = 3 # valid

Note that the matrix is "y" address major, in other words, the "y index" comes before the "x index".

print Matrix[0][0] # prints 1
x, y = 0, 6
print Matrix[x][y] # prints 3; be careful with indexing!

Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use "x" for both the inner and outer lists, and want a non-square Matrix.

Create multidimensional array in for loop

You can do something like this:

var squares = new Array();
for(var i = 0; i <= 8; i++)
{
squares[i] = new Array();
for(var j = (i * 20) + 1; j <= 20 * i + 20; j++)
if (squares[i] == null)
squares[i] = j;
else
squares[i].push(j);
}

Output comes like:

array[0][1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
array[1][21,22,23,24,25,26,27....]

How can I create multidimensional arrays of arbitrary sizes?

Your map is declared as a multidimensional array [4][4]bool, and the length of an array is part of the compile time type (based on my understanding of https://ziglang.org/documentation/master/#Slices).

As you've figured out from printMap if you want these sizes to be defined at runtime, you'll have to use slices (types with a pointer and length) e.g. [][]bool

To get your example working using the signature printMap(map: []const []bool), you could do the following:

var a = [_]bool{ false, false, true };
var b = [_]bool{ false, true, false };

const map = [_][]bool{
a[0..], // Make it a slice using slice syntax
&b, // Or make it a slice by coercing *[N]T to []T
};

var c: []const []bool = map[0..]; // Pass it as a slice of slices
printMap(c);

To create arrays of multidimensional slices of arbitrary sizes, you'd need to have some buffers to store the data.
You could use some static memory, or allocate some as needed, one approach might be this:

fn buildMap(x: u8, y: u8, allocator: *std.mem.Allocator) ![][]bool {
var map: [][]bool = undefined;
map = try allocator.alloc([]bool, x);
for (map) |*row| {
row.* = try allocator.alloc(bool, y);
}
return map;
}

Which should work with printMap(map: []const []bool).

Another approach would be to use a single dimensional array/buffer, and index into it appropriately, but that doesn't quite answer your question. I'm fairly new to the language, so there might be subtleties I've missed.

Create multidimensional array from multiple arrays in PHP

You can simply use array_combine:

Creates an array by using one array for keys and another for its
values

$arr1 = array(0 => 'label', 1 => 'data');
$arr2 = array(0 => 1, 1 => 2);
$arr3 = array_combine($arr1, $arr2);

print_r($arr3);

Result:

Array
(
[label] => 1
[data] => 2
)

Try it

How to create multidimensional array in python 3

array = []
for i in range(0,5):
array.append({"id":i,"result":{"text":f"id {i}"}})
print(array)

#to json
import json
print(json.dumps(array))

output

[{'id': 0, 'result': {'text': 'id 0'}}, {'id': 1, 'result': {'text': 'id 1'}}, {'id': 2, 'result': {'text': 'id 2'}}, {'id': 3, 'result': {'text': 'id 3'}}, {'id': 4, 'result': {'text': 'id 4'}}]

[{"id": 0, "result": {"text": "id 0"}}, {"id": 1, "result": {"text": "id 1"}}, {"id": 2, "result": {"text": "id 2"}}, {"id": 3, "result": {"text": "id 3"}}, {"id": 4, "result": {"text": "id 4"}}]

C: declare multidimensional arrays without size?

Is there no way to declare a multidimensional array without specifying its size?

You have to know all dimensions except the "last"/the most "upper" dimension. Because to allocate memory you have to know the size of the element in the array. As for your case it's simple - you allocate an array of two doubles.

You can do a pointer to an array of 2 double elements:

double (*arr)[2];
// you can normally allocate
arr = malloc(sizeof(*arr) * amount);
// and normally iterate
for (size_t i = 0; i < amount; ++i) {
for (size_t j = 0; j < 2; ++j) {
printf("%f", arr[i][j]);
}
}

The type of *arr is double[2], so the sizeof(*arr) will properly resolve as sizeof(double[2]).



Related Topics



Leave a reply



Submit