This post will discuss how to display two-dimensional arrays in JavaScript.

A two-dimensional array is an array of arrays, where each sub-array represents a row or a column of data. Here are some examples of how to display two-dimensional arrays in JavaScript given an array:

1. Using console.log() function

This is a simple and convenient way to display two-dimensional arrays in JavaScript for debugging purposes. The console.log() function prints a message to the web console, which is a tool for developers to inspect and debug web pages. We can use it to print a two-dimensional array as a table by passing the array as an argument. For example, if we have an array and we want to print it as a table, we can do:

Download  Run Code

 
The output will look like [[1, 2, 3], [4, 5, 6], [7, 8, 9]] on the standard output, but something like below in the browser console. We can expand each sub-array to see its elements by clicking on the arrow icons.


(3) [Array(3), Array(3), Array(3)]
> 0: (3) [1, 2, 3]
> 1: (3) [4, 5, 6]
> 2: (3) [7, 8, 9]
length: 3
> [[Prototype]]: Array(0)

2. Using join() function

The join() function creates and returns a new string by concatenating all of the elements in an array, separated by commas or a specified separator string. We can use it to print a two-dimensional array as a string by joining each sub-array with a newline character (\n) and then joining the resulting array with another separator. For example, the following code uses the map() function to iterate over the elements of the nested array and concatenate them with the separator.

Download  Run Code

Output:

1 2 3
4 5 6
7 8 9

 
We can change the separators to suit our needs. We can also use a for loop with this function to print each element of the two-dimensional array on the same line with a separator. For example:

Download  Run Code

Output:

1, 2, 3
4, 5, 6
7, 8, 9

3. Using spread operator

The spread syntax (…) is a new feature of JavaScript that allow expanding iterables into individual elements. We can use the spread operator to print a two-dimensional array by expanding each sub-array and pass it to the console.log() function. Here’s an example of this approach:

Download  Run Code

Output:

1 2 3
4 5 6
7 8 9

4. Using document.write() function

The document.write() function can write any HTML or text content to the document. We can use this function to print each element of the two-dimensional array in an HTML table. For example:

Download  Run Code

That’s all about displaying two-dimensional arrays in JavaScript.