How to useArray.from() Method in Javascript

The JavaScript Array from() method returns an Array object from any object with a length property or an iterable object. 

Example: This example shows the implemention of above-explained approach.

Javascript
const rows = 3;
const columns = 4;
const matrix = Array.from({ length: rows }, () => 
               new Array(columns).fill(0));
console.log(matrix);

Output
[ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ] ]

How to create two dimensional array in JavaScript ?

A two-dimensional array in JavaScript is an array of arrays, used to represent data in a matrix or grid format. It’s useful for organizing data in rows and columns, such as tables, spreadsheets, or game boards, facilitating complex data manipulation and storage.

We can create a 2D array in many ways:

Table of Content

  • Approach 1: Using a nested for loop
  • Approach 2: Use the literal notation
  • Approach 3: Using Array.from() Method
  • Approach 4: Using Array.fill() Method
  • Approach 5: Using Array.prototype.map() Method

Similar Reads

Approach 1: Using a nested for loop

In this approach, we are using for loop for the creation of a 2D array. we are iterating the loop row*col times....

Approach 2: Use the literal notation

In this approach, we are declaring a 2D array originally and storing it to in a variable....

Approach 3: Using Array.from() Method

The JavaScript Array from() method returns an Array object from any object with a length property or an iterable object....

Approach 4: Using Array.fill() Method

In this method, we will use the fill() method and map method for creating the two-dimensional array in Javascript....

Approach 5: Using Array.prototype.map() Method

The Array.prototype.map() method creates a new array populated with the results of calling a provided function on every element in the calling array. This approach can be leveraged to create a 2D array by mapping over an array of rows and columns....

Contact Us