6ļøāƒ£

5.6 2D Arrays

5.6 2D Arrays

JavaScript does not provide the multidimensional array natively.
However, you can create a multidimensional array by defining an array of elements, where each element is also another array.
Ā 
For this reason, we can say that a JavaScript multidimensional array is an array of arrays. The easiest way to define a multidimensional array is to use the array literal notation.
Ā 
To declare an empty multidimensional array, you use the same syntax as declaring one-dimensional array:
let activities = [];
The following example defines a two-dimensional array named activities:
let activities = [ ['Work', 9], ['Eat', 1], ['Commute', 2], ['Play Game', 1], ['Sleep', 7] ];
Here's what the code is doing conceptually:
In the 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:
console.table(activities); // output: ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā” ā”‚ (index) ā”‚ 0 ā”‚ 1 ā”‚ ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¼ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¼ā”€ā”€ā”€ā”¤ ā”‚ 0 ā”‚ 'Work' ā”‚ 9 ā”‚ ā”‚ 1 ā”‚ 'Eat' ā”‚ 1 ā”‚ ā”‚ 2 ā”‚ 'Commute' ā”‚ 2 ā”‚ ā”‚ 3 ā”‚ 'Play Game' ā”‚ 1 ā”‚ ā”‚ 4 ā”‚ 'Sleep' ā”‚ 7 ā”‚ ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”˜

Practice

You can add practice problems here if you want. Follow the format below.
Ā 
āš–ļø
Copyright Ā© 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.