JavaScript. Two-dimensional arrays. Arrays within arrays. Three-dimensional arrays

Two-dimensional arrays. Arrays within arrays. Three-dimensional arrays


Contents


Search other resources:

1. Types of two-dimensional arrays. Declaring and using a two-dimensional array using the new keyword

JavaScript allows you to create a two-dimensional array of two types:

  • with the same number of elements in each row (Figure 1-a);
  • with an arbitrary number of elements in each row (Figure 1-b).

However, each element can also be an array or other complex object.

JavaScript. Types of two-dimensional arrays

Figure 1. Types of two-dimensional arrays. The number of elements in each row is the same (a) and arbitrary (b)

 

2. A literal definition of a two-dimensional array [ ]. General form

With a literal definition of a two-dimensional array, the array elements are specified in outer square brackets [], which, in turn, contain sets of elements taken in inner square brackets.

In the most general form, creating a two-dimensional array of size M×N (all rows have the same size) is as follows

var ArrayName =
  [
    [ item11, item12, ..., item1N],
    [ item21, item22, ..., item2N],
    ...
    [ itemM1, itemM2, ..., itemMN]
  ]

here

  • ArrayName is the name of the declared array;
  • M – the number of rows in the array;
  • N – the number of columns in the array;
  • item11, item12, …, itemMN – array elements. These elements can be objects of any type (number, string, etc.) and even other arrays.

If the number of elements in each line is different, then the general form of declaring such an array in a literal way can be, for example

var ArrayName =
  [
    [ item11, item12, ..., item1_N1 ],
    [ item21, item22, ..., item2_N2 ],
    ...
    [ itemM1, itemM2, ..., itemM_NM ]
  ]

here

  • N1, N2, NM – respectively, the number of elements in line 1 (position 0), line 2 and line M. That is, the number of elements in each line is different.

 

3. An example of creating a two-dimensional table with the same number of elements per row in a literal way

The example creates a two-dimensional table shown in Figure 2.

Two-dimensional tableFigure 2. Two-dimensional table

The matrix is created in two different ways

// Two-dimensional arrays

// Way 1.
// 1. Create a two-dimensional matrix of integers of size 3*4
var M = []
M[0] = [ 2, 8, 4, 1 ] // First row of the matrix
M[1] = [ 4, 2, 0, 9 ] // Second row of the matrix
M[2] = [ 1, 7, 5, 4 ] // Third row of the matrix

// 2. Output the matrix
document.write("M:<br>")
for (var i=0; i<3; i++)
{
  for (var j=0; j<4; j++)
    document.write(M[i][j] + " ")
  document.write("<br>")
}

// Way 2.
var MM =
[
  [ 2, 8, 4, 1 ],
  [ 4, 2, 0, 9 ],
  [ 1, 7, 5, 4 ]
]

// 2. Output the matrix
document.write("MM:<br>")
for (var i=0; i<3; i++)
{
  for (var j=0; j<4; j++)
    document.write(MM[i][j] + " ")
  document.write("<br>")
}

Result

M:
2 8 4 1
4 2 0 9
1 7 5 4
MM:
2 8 4 1
4 2 0 9
1 7 5 4

 

4. Defining a two-dimensional array using the new operator

With this method, a two-dimensional array is defined using the new keyword, the name of the Array class, and parentheses around the elements of the array.

The following is the general form of creating a two-dimensional array where the number of elements in all rows is the same

var ArrayName = new Array(
  new Array(item11, item12, ..., item1N),
  new Array(item21, item22, ..., item2N),
  ...
  new Array(itemM1, itemM2, ..., itemMN)
)

here

  • ArrayName – the name of the created array;
  • M – the number of rows in the array;
  • N – the number of items in row (the number of columns);
  • item11, item12, itemMN – array items. These can be strings, numbers, objects, and other arrays (subarrays).

If an array contains a different number of elements in each row, then the general form of creating such an array is as follows

var ArrayName = new Array(
  new Array(item11, item12, ..., item1_N1),
  new Array(item21, item22, ..., item2_N2),
  ...
  new Array(itemM1, itemM2, ..., itemM_NM)
)

here

  • N1, N2, NM – respectively, the number of elements in row 1 (position 0), row 2 and row M. That is, the number of elements in each row is different.

When declaring two-dimensional arrays, you can combine this method of creating an array with the literal method (item 2).

 

5. An example of creating an array of numbers with different lengths of strings using the new operator

In the example, using the new operator, an array of numbers is created, which is shown in Figure 3.

JavaScript. An array of numbers with different length stringsFigure 3. An array of numbers with different length strings

The example text is as follows

// Two-dimensional and multidimensional arrays

// Create an array using the new operator.
// The length of each string in the array is different.

// 1. Declaring an array and filling with values
var M = new Array(
  new Array( 5, 9, 3),
  new Array( 8, 1.23, 2.99, 6.54, 5.4),
  new Array( 7.2, 2, -40.6, -1.03)
)

// 2. Output array M element by element
document.write("M:<br>")
for (var i=0; i<M.length; i++)
{
  for (var j=0; j<M[i].length; j++)
    document.write(M[i][j] + " ");
  document.write("<br>")
}

// 3. Print the array M in rows
document.write("-----------------------<br>")
document.write("M:<br>")
for (var i=0; i<M.length; i++)
  document.write(M[i]+"<br>")
document.write("-----------------------<br>")

// 3. Output a single array element in an array
document.write(M[1][2]+"<br>") // 2.99

Result

M:
5 9 3
8 1.23 2.99 6.54 5.4
7.2 2 -40.6 -1.03
-----------------------
M:
5,9,3
8,1.23,2.99,6.54,5.4
7.2,2,-40.6,-1.03
-----------------------
2.99

 

6. Features of using arrays in arrays

As mentioned above (item 1), an array element can be another array of any dimension. Figure 4 shows array elements that are also arrays. To access element 7 of the subarray [2, 7, 3], you must refer to M[0][0][1].

JavaScript. Array within array

Figure 4. Array within array

 

7. An example of creating array within array in the literal way

 

// Two-dimensional and multidimensional arrays

// Create an array within an array in a literal way
var M = []
var m1 = [2, 7, 3]

M[0] = [ 5, m1, 9 ] // the first row of the matrix
M[1] = [ 8, 1.23, [] , "abc" ] // the second row of the matrix
M[2] = [ [7.2, 1 ], [ 'a', 2 ] ] // the third row of the matrix

// 2. Show array
document.write("M:<br>")
for (var i=0; i<3; i++)
{
  for (var j=0; j<M[i].length; j++)
    document.write(M[i][j] + " ")
  document.write("<br>")
}

// Output a single array element in an array
document.write(M[0][1][0]+"<br>") // 7
document.write(M[2][0][1]+"<br>") // 1
document.write(M[2][1][0]+"<br>") // 'a'

Result

M:
5 2,7,3 9
8 1.23 abc
7.2,1 a,2
2
1
a

 

8. An example of creating an array within an array using a combination of the new operator and a literal method

When creating a multidimensional array, you can combine the creation of an array with the new operator and the literal method.

// Two-dimensional and multidimensional arrays

// Create an array within an array using the new operator.
// Form an array in which the name of the season corresponds
// to a certain list of months.
// M:
// [ "December", "January", "February"]
// [ "March", "April", "May"]
// [ "June", "July", "August" ]
// [ "September", "October", "November"]

// 1. Create an array of months corresponding to the seasons
var M = new Array(
  ["December", "January", "February"],
  ["March", "April", "May"],
  ["June", "July", "August"],
  ["September", "October", "November"]
)

// 2. Display the array M
for (var i=0; i<M.length; i++)
  document.write(M[i]+"<br>");

// 3. Output a single array element in the array
document.write(M[1][2]+"<br>") // May
document.write(M[3][0]+"<br>") // September

Result

December,January,February
March,April,May
June,July,August
September,October,November
May
September

 

9. Creates a two-dimensional array of the given size. The size is set from the keyboard. The length property

Task.

Create a two-dimensional array of size m×n, where m is the number of rows, n is the number of columns. Values m, n are entered from the keyboard. Fill array elements with values 1.

Solution.

After m is entered, the array’s length property is set to the appropriate values.

// Two-dimensional and multidimensional arrays

// Task. Create an array of given size m*n,
// where m, n are entered from the keyboard.
// Fill the array with values 1.

// 1. Input m, n
var m = prompt("m = ")
var n = prompt("n = ")

// 2. Array declaration
var A = new Array()

// 3. Specify the number of rows
A.length = m;

// 4. Specify the number of columns
for (var i=0; i<m; i++)
{
  // Create a subarray in the array
  A[i] = new Array()

  // Set the length of the array
  A[i].length = n
}

// 5. Fill array A with values 1
for (var i=0; i<A.length; i++)
  for (var j=0; j<A[i].length; j++)
    A[i][j] = 1

// 6. Display array A on the screen
document.write("A:<br>")
for (var i=0; i<A.length; i++)
{
  for (var j=0; j<A[i].length; j++)
    document.write(A[i][j]+" ")
  document.write("<br>")
}

Result

A:
1 1 1 1
1 1 1 1
1 1 1 1

 

10. Creation of a three-dimensional array. The length property

When creating a three-dimensional array, the dimension of each dimension is set using the length property, as shown below

// Create a one-dimensional array of dimension m
A = new Array()
A.length = m

// Add second dimension n,
// get a two-dimensional array of size m*n
A[0] = new Array(); A[0].length = n
A[1] = new Array(); A[1].length = n
...
A[m-1] = new Array(); A[m-1].length = n

// Add third dimension [k]
A[0][0] = new Array(); A[0][0].length = k
A[0][1] = new Array(); A[0][1].length = k
...
A[0][n-1] = new Array(); A[0][n-1].length = k
A[1][0] = new Array(); A[1][0].length = k
...
A[1][n-1] = new Array(); A[1][n-1].length = k
...
A[m-1][0] = new Array(); A[m-1][0].length = k
...
A[m-1][n-1] = new Array(); A[m-1][n-1].length = k

The above snippet creates a 3D array named A with size m×n×k. Of course, it is more expedient to build an array in a loop (see the next example).

After that, the element of the three-dimensional array can be assigned a value according to the pattern

A[x][y][z] = value

here

  • A – array name;
  • x – the coordinate of the first dimension of the array, x = 0, 1, …, m-1;
  • y – coordinate of the second array dimension, y = 0, 1, …, n-1;
  • z – coordinate of the third dimension of the array, z = 0, 1, …, k-1;
  • value – some value.

 

11. An example of creating a three-dimensional array according to the given dimensions m×n×k. Array elements are filled with random integers

If the size of the created array is known in advance, then the length property is used in this case. Changing the value of this property (on the left side of the operator) allows you to allocate memory for a given number of elements in one dimension of the array.

The example below demonstrates the creation of a three-dimensional array of size m×n×k, where m, n, k are entered from the keyboard. Array elements are filled with random numbers in the range [5, 10].

The Math.random() function is used to get a random number.

// Two-dimensional and multidimensional arrays

// Task. Create an array of the given size m*n,
// where m, n are entered from the keyboard.
// Fill the array with values 1.

// 1. Input m, n, k
var m = prompt("m = ")
var n = prompt("n = ")
var k = prompt("k = ")

// 2. Array declaration, create an empty array
var A = new Array()

// 3. Set the number of elements along the X axis
A.length = m;

// 4. Set the number of elements along the Y axis
for (var i=0; i<m; i++)
{
  // Create a subarray in an array,
  // allocate memory for another dimension
  A[i] = new Array()

  // Set the length of the array
  A[i].length = n
}

// 5. Set the number of elements along the Z axis
for (var i=0; i<A.length; i++)
  for (var j=0; j<A[i].length; j++)
  {
    // Allocate memory for the third dimension
    A[i][j] = new Array()

    // Set the length of the third dimension of the array
    A[i][j].length = k
  }

// 6. Fill array with random values
for (var i=0; i<A.length; i++)
  for (var j=0; j<A[i].length; j++)
    for (var t=0; t<A[i][j].length; t++)
      A[i][j][t] = 5 + parseInt(Math.random()*(10-5+1))

// 7. Display array A element by element
document.write("A:<br>")
for (var i=0; i<A.length; i++)
  for (var j=0; j<A[i].length; j++)
    for (var t=0; t<A[i][j].length; t++)
      document.write("A["+i+"]["+j+"]["+t+"] = "+A[i][j][t]+"<br>")

For the specified

m = 2
n = 3
k = 4

the program produced the following result

A:
A[0][0][0] = 9
A[0][0][1] = 5
A[0][0][2] = 5
A[0][0][3] = 10
A[0][1][0] = 9
A[0][1][1] = 7
A[0][1][2] = 10
A[0][1][3] = 8
A[0][2][0] = 5
A[0][2][1] = 6
A[0][2][2] = 10
A[0][2][3] = 6
A[1][0][0] = 6
A[1][0][1] = 6
A[1][0][2] = 7
A[1][0][3] = 5
A[1][1][0] = 6
A[1][1][1] = 6
A[1][1][2] = 10
A[1][1][3] = 6
A[1][2][0] = 9
A[1][2][1] = 7
A[1][2][2] = 5
A[1][2][3] = 6

 


Related topics