This post will discuss how to create an array of arrays in JavaScript.

There are several ways to construct an array of arrays in JavaScript, which is a data structure that can store multiple arrays as its elements. An array of arrays is also known as a two-dimensional array or a matrix. Here are some common functions:

1. Using an array literal

This is the easiest and most common way to create an array of arrays. An array literal is a pair of square brackets [] that can contain comma-separated values. To create an array of arrays, we just need to use the brackets with nested arrays as values. Here’s an example:

Download  Run Code

2. Using Array constructor

This is another way to create an array of arrays, but it is less preferred than the array literal. The Array constructor is a function that can create an array object with a given length or elements. To create an array of arrays, we can either use the constructor with nested arrays as arguments or with a single argument that specifies the length of the outer array. Here’s an example:

Download  Run Code

3. Using Array.push() function

The Array.push() function adds one or more elements to the end of an array, and returns the new length of the array. We can use this function to append subarrays to an existing array. Here’s an example:

Download  Run Code

4. Using Array.of() function

The Array.of() function creates a new array instance from a variable number of arguments. We can use this function to create an array of arrays by passing subarrays as arguments. Here’s an example:

Download  Run Code

5. Using a loop

We can use a loop to create an array of arrays dynamically, based on some logic or condition. For example, we can use a for loop to create an array of arrays that contain the multiplication table from 1 to 10:

Download  Run Code

6. Using Array.map() function

To create an array of arrays, we can use the Array.map() function to map each element of an existing array to a subarray. This function creates a new array with the results of calling a function on every element in the original array. The syntax is array.map(function(element, index, array) {return value;}), where function takes an element, its index, and the original array as parameters and returns a value for the new array. Here’s an example:

Download  Run Code

That’s all about creating an array of arrays in JavaScript.