- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Constructing 2-D array based on some constraints 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 - 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]];
Therefore, let’s write the code for this function −
Example
The code for this will be −
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
The output in the console will be −
[ [ 10, 10, 10 ], [ 10, 10, 10 ] ]
Advertisements
To Continue Learning Please Login
Login with Google