
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 ] ]
- Related Articles
- Build maximum array based on a 2-D array - JavaScript
- Constructing a string based on character matrix and number array in JavaScript
- Constructing a sentence based on array of words and punctuations using JavaScript
- Constructing an array of smaller elements than the corresponding elements based on input array in JavaScript
- Constructing product array in JavaScript
- Constructing multiples array - JavaScript
- Sort array based on another array in JavaScript
- Filter array based on another array in JavaScript
- Sorting Array based on another array JavaScript
- Reorder array based on condition in JavaScript?
- Modify an array based on another array JavaScript
- Shuffling string based on an array in JavaScript
- Constructing array from string unique characters in JavaScript
- Constructing largest number from an array in JavaScript
- Decrypting source message from a code based on some algorithm in JavaScript

Advertisements