How to useArray.from() with a Mapping Function in Javascript
Using Array.from() with a mapping function, the code creates a two-dimensional array by specifying the number of rows and columns. Each cell is initialized using the mapping function to fill the array with a specified initial value.
Example
let rows = 3;
let cols = 4;
let initialValue = undefined;
let arr = Array.from({ length: rows }, () => Array(cols).fill(initialValue));
// Example usage
console.log(arr);
Output
[ [ undefined, undefined, undefined, undefined ], [ undefined, undefined, undefined, undefined ], [ undefined, undefined, undefined, undefined ] ]
How to Declare Two Dimensional Empty Array in JavaScript ?
In this article, we are going to learn about Declare two-dimensional empty array by using JavaScript. A two-dimensional array is also known as a 2D array. It is a data structure in JavaScript that can hold values in rows and columns form. It is an array of arrays. Each element in a 2D array is accessible using two indices, and it is represented as an array[rowIndex][columnIndex].
There are several methods that can be used to add elements to Declare an empty two-dimensional array in JavaScript, which are listed below:
Table of Content
- Using a Loop
- Using the Array() Constructor
We will explore all the above methods along with their basic implementation with the help of examples.
Contact Us