How to make an array of JavaScript arrays

Find out how to create an array of arrays in JavaScript with an example: const arr = [1,2], [3.4]].

Creating an Array of JavaScript Arrays

An array of JavaScript arrays is an array that contains arrays as its elements. These sub-arrays can be of any type, including other arrays, objects, strings, numbers, etc. Here's an example of how to create an array of JavaScript arrays:


var arrOfArrays = [
  ['a', 'b', 'c'],
  [1, 2, 3],
  [{name: 'John', age: 25}, {name: 'Mary', age: 22}]
];

In this example, arrOfArrays is an array containing three elements. The first element is an array of three strings (a, b, c), the second is an array of three numbers (1, 2, 3), and the third is an array of two objects, each with two properties (name and age).

You can also use the Array.from() method to create an array of JavaScript arrays. Here's an example:


var arrOfArrays = Array.from([
  ['a', 'b', 'c'],
  [1, 2, 3],
  [{name: 'John', age: 25}, {name: 'Mary', age: 22}]
]);

In this example, arrOfArrays is an array containing three elements, just like in the previous example. However, this time we used the Array.from() method to create the array.

You can also use the Array.prototype.slice() method to create an array of JavaScript arrays. Here's an example:


var arrOfArrays = [
  ['a', 'b', 'c'],
  [1, 2, 3],
  [{name: 'John', age: 25}, {name: 'Mary', age: 22}]
].slice();

In this example, arrOfArrays is an array containing three elements, just like in the previous examples. This time we used the Array.prototype.slice() method to create the array.

No matter which method you choose to create an array of JavaScript arrays, the result will be an array of sub-arrays, each containing its own set of elements.

Answers (0)