1// declaration of a two-dimensional array
2// 5 is the number of rows and 4 is the number of columns.
3const matrix = new Array(5).fill(0).map(() => new Array(4).fill(0));
4
5console.log(matrix[0][0]); // 0
6
1/*having the previous array easy to make is very useful*/
2
3function Array2D(x, y){
4 let arr = Array(x);
5 for(let i = 0; i < y; i++){
6 arr[i] = Array(y);
7 }
8 return arr;
9}
10
11function Array3D(x, y, z){
12 let arr = Array2D(x, y);
13 for(let i = 0; i < y; i++){
14 for(let j = 0; j < z; j++){
15 arr[i][j] = Array(z);
16 }
17 }
18 return arr;
19}
20
21function Array4D(x, y, z, w){
22 let arr = Array3D(x, y, z);
23 for(let i = 0; i < x; i++){
24 for(let j = 0; j < y; j++){
25 for(let n = 0; n < z; n++){
26 arr[i][j][n] = Array(w);
27 }
28 }
29 }
30 return arr;
31}
32/*making the array*/
33let myArray = Array4D(10, 10, 10, 10);
1// function to create a n-dimentional array
2function createArray(length) {
3 var arr = new Array(length || 0),
4 i = length;
5
6 if (arguments.length > 1) {
7 var args = Array.prototype.slice.call(arguments, 1);
8 while(i--) arr[length-1 - i] = createArray.apply(this, args);
9 }
10
11 return arr;
12}
13
14//eg.
15createArray(); // [] or new Array()
16
17createArray(2); // new Array(2)
18
19createArray(3, 2); // [new Array(2),
20 // new Array(2),
21 // new Array(2)]
1var array = [
2 ["0, 0", "1, 0", "2, 0", "3, 0", "4, 0"],
3 ["0, 1", "1, 1", "2, 1", "3, 1", "4, 1"],
4 ["0, 2", "1, 2", "2, 2", "3, 2", "4, 2"],
5 ["0, 3", "1, 3", "2, 3", "3, 3", "4, 3"],
6 ["0, 4", "1, 4", "2, 4", "3, 4", "4, 4"],
7 ]; // Think of it as coordinates, array[x, y] x = 0; y = 0; is "0, 0" on
8 // this grid
9
10console.log(array[3][3]); // returns "3, 3"
11// If you use graphics (ex: p5js or JS Canvas) then this will be a 5x5 map.
12// Useful for roguelikes and/or raycasters.
1//2D array
2let activities = [
3 ['Work', 9],
4 ['Eat', 1],
5 ['Commute', 2],
6 ['Play Game', 1],
7 ['Sleep', 7]
8];
1var grid = [];
2iMax = 3;
3jMax = 2;
4count = 0;
5
6 for (let i = 0; i < iMax; i++) {
7 grid[i] = [];
8
9 for (let j = 0; j < jMax; j++) {
10 grid[i][j] = count;
11 count++;
12 }
13 }
14
15// grid = [
16// [ 0, 1 ]
17// [ 2, 3 ]
18// [ 4, 5 ]
19// ];
20
21console.log(grid[0][2]); // 4