AppDividend
Latest Code Tutorials

JavaScript 2D Array: Create Two Dimensional Array in JavaScript

0

JavaScript does not provide the multi-dimensional array natively or provide any method to define the 2D array. However, you can create a multi-dimensional array by defining the array of items, where each item is also another array.

JavaScript 2D Array

To create the 2D array in JavaScript, we have to create an array of array. To declare a 2D array, you use the same syntax as declaring a one-dimensional array.

Syntax of 1D Array

let data = [];

To declare the 2D array, use the following syntax.

Syntax of 2D Array

let data = [
  [],
  [],
  []
];

In the above code, we have defined an empty 2D array.

Let’s define a 2D array with some values.

// app.js

let data = [
  ['Millie', 15],
  ['Finn', 17],
  ['Dustin', 17]
];

console.log(data);

Output

[ [ 'Millie', 15 ], [ 'Finn', 17 ], [ 'Dustin', 17 ] ]

In the above data array, the first dimension represents the name of the actor, and the second one shows the age of each actor.

JavaScript console.table()

The console.table() method displays the tabular data as a table. The table() function takes one mandatory argument data, which must be the array or an object, and one additional optional parameter columns.

It logs data as a table. Each item in the array (or enumerable property if data is the object) will be the row in a table. We can use the console.table() method to display the above output.

// app.js

let data = [
  ['Millie', 15],
  ['Finn', 17],
  ['Dustin', 17]
];

console.table(data);

Output

 node app
┌─────────┬──────────┬────┐
│ (index) │    0     │ 1  │
├─────────┼──────────┼────┤
│    0    │ 'Millie' │ 15 │
│    1    │  'Finn'  │ 17 │
│    2    │ 'Dustin' │ 17 │
└─────────┴──────────┴────┘

Note that the (index) column is for the illustration that indicates the indices of the inner array.

Accessing 2D Array in JavaScript

To access an item of the 2D array, you first use square brackets to access an item of the outer array that returns an inner array; and then use another square bracket to access the element of the internal array.

// app.js

let data = [
  ['Millie', 15],
  ['Finn', 17],
  ['Dustin', 17]
];

console.log('The age of Millie is:', data[0][1]);

Output

The age of Millie is: 15

Adding elements to the 2D array

To add elements to the 2D array, use the Array methods such as the array push() method.

// app.js

let data = [
  ['Millie', 15],
  ['Finn', 17],
  ['Dustin', 17]
];

data.push(['Sadie', 15], ['Caleb', 18]);
console.log(data);

Output

[
  [ 'Millie', 15 ],
  [ 'Finn', 17 ],
  [ 'Dustin', 17 ],
  [ 'Sadie', 15 ],
  [ 'Caleb', 18 ]
]

In this example, we already have a 2D array with three elements. Using the push() method, we are adding two more elements to the array, and from the above output, you can see that we have added two items successfully to the 2D array.

To insert an element in the middle of the array, use the JavaScript array splice() method. The following code inserts an element in the second position of the data array and displays it in the tabular format.

// app.js

let data = [
  ['Millie', 15],
  ['Finn', 17],
  ['Dustin', 17]
];

data.splice(1, 0, ['Sadie', 15])
console.table(data);

Output

┌─────────┬──────────┬────┐
│ (index) │    0     │ 1  │
├─────────┼──────────┼────┤
│    0    │ 'Millie' │ 15 │
│    1    │ 'Sadie'  │ 15 │
│    2    │  'Finn'  │ 17 │
│    3    │ 'Dustin' │ 17 │
└─────────┴──────────┴────┘

You can see that it has added a new element at position 1.

Adding a dynamic property to the 2D array

The following example calculates the percentage of the age of each character based on 80 years span and appends the percentage to the inner array.

// app.js

let data = [
  ['Millie', 15],
  ['Finn', 17],
  ['Dustin', 17]
];

data.forEach(age => {
  let percentage = ((age[1] / 80) * 100).toFixed();
  age[2] = percentage + '%';
});

console.table(data);

Output

┌─────────┬──────────┬────┬───────┐
│ (index) │    0     │ 1  │   2   │
├─────────┼──────────┼────┼───────┤
│    0    │ 'Millie' │ 15 │ '19%' │
│    1    │  'Finn'  │ 17 │ '21%' │
│    2    │ 'Dustin' │ 17 │ '21%' │
└─────────┴──────────┴────┴───────┘

To append a new property in a 2D array, we used JavaScript array forEach() method to iterate the inner array one by one and add the percentage to the array. When we see in the table, it will become a column of the table.

Removing elements from the JavaScript 2D array

To remove an item from an array, you use the array pop() or array splice() method.

// app.js

let data = [
  ['Millie', 15],
  ['Finn', 17],
  ['Dustin', 17]
];

data.pop();

console.table(data);

Output

┌─────────┬──────────┬────┐
│ (index) │    0     │ 1  │
├─────────┼──────────┼────┤
│    0    │ 'Millie' │ 15 │
│    1    │  'Finn'  │ 17 │
└─────────┴──────────┴────┘

Iterating 2D array

To iterate the 2D array in JavaScript, use the forEach() method twice.

// app.js

let data = [
  ['Millie', 15],
  ['Finn', 17],
  ['Dustin', 17]
];

data.forEach(arr => {
  arr.forEach(d => console.log(d));
});

Output

Millie
15
Finn
17
Dustin
17

So, if you want to iterate each element of the 2D or multiple dimensional arrays, then you have to use the forEach() method two times because it is the arrays inside an array.

Conclusion

JavaScript multi-dimensional array almost works as a 1D array. The two-dimensional array is a collection of elements that share a common name, and they are organized as the matrix in the form of rows and columns. The two-dimensional array is an array of arrays, so we create the array of one-dimensional array objects.

See also

JavaScript array some()

JavaScript array contains

JavaScript  array isArray()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.