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.
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
Contact Us