- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Creating a two-dimensional array with given width and height in JavaScript
We are required to write a JavaScript function that creates a multi-dimensional array based on some inputs. It should take in three elements, namely −
- row − the number of subarrays to be present in the array,
- col − the number of elements in each subarray
- val minus; the val of each element in the subarrays
For example, if the three inputs are 2, 3, 10
Then the output should be −
const output = [[10, 10, 10], [10, 10, 10]];
Example
Following is the code −
const row = 2; const col = 3; const val = 10; const constructArray = (row, col, val) => { const res = []; for(let i = 0; i < row; i++){ for(let j = 0; j < col; j++){ if(!res[i]){ res[i] = []; }; res[i][j] = val; }; }; return res; }; console.log(constructArray(row, col, val));
Output
This will produce the following output in console −
[ [ 10, 10, 10 ], [ 10, 10, 10 ] ]
- Related Articles
- How to form a two-dimensional array with given width (columns) and height (rows) in JavaScript ?
- Get the width and height of a three-dimensional array
- Split one-dimensional array into two-dimensional array JavaScript
- Transpose of a two-dimensional array - JavaScript
- How to create a two dimensional array in JavaScript?
- Creating a JavaScript array with new keyword.
- Difference Between One-Dimensional (1D) and Two-Dimensional (2D) Array
- Get the Inner product of a One-Dimensional and a Two-Dimensional array in Python
- Creating an associative array in JavaScript with push()?
- How to split comma and semicolon separated string into a two-dimensional array in JavaScript ?
- Alternating sum of elements of a two-dimensional array using JavaScript
- Multi-Dimensional Array in Javascript
- Display a two-dimensional array with two different nested loops in matrix form PHP?
- JAVA Program to Calculate Radius of Circle with Given Width and Height of Arc
- Working with two-dimensional array at runtime in C programming

Advertisements