To declare an empty multidimensional array, you use the same syntax as declaring one-dimensional array:
The following example defines a two-dimensional array named
activities array, the first dimension represents the activity and the second one shows the number of hours spent per day for each.
To show the
activities array in the console, you use the
console.table() method as follows:
The following illustrates the output:
Note that the
(index) column is for the illustration that indicates the indices of the inner array.
To access an element of the multidimensional array, you first use square brackets to access an element of the outer array that returns an inner array; and then use another square bracket to access the element of the inner array.
The following example returns the second element of the first inner array in the
activities array above:
You can use the Array methods such as
splice() to manipulate elements of a multidimensional array.
For example, to add a new element at the end of the multidimensional array, you use the
push() method as follows:
To insert an element in the middle of the array, you use the
splice() method. The following inserts an element in the second position of the activities array:
Here is the output:
This example calculates the percentage of the hours spent on each activity and appends the percentage to the inner array.
The following shows the output in the console:
To remove an element from an array, you use the
For example, the following statement removes the last element of the
Similarly, you can remove the elements from the inner array of the multidimensional array by using the
pop() method. The following example removes the percentage element from the inner arrays of the
To iterate a multidimensional array, you use a nested for loop as in the following example.
The first loop iterates over the elements of the outer array and the nested loop iterates over elements of the inner array.
The following shows the output of the script in the console:
Or you can use the
forEach() method twice: