- 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
How to form a two-dimensional array with given width (columns) and height (rows) in JavaScript ?
We are required to write a JavaScript function that takes in three arguments −
height --> no. of rows of the array width --> no. of columns of the array val --> initial value of each element of the array
Then the function should return the new array formed based on these criteria.
Example
The code for this will be −
const rows = 4, cols = 5, val = 'Example'; const fillArray = (width, height, value) => { const arr = Array.apply(null, { length: height }).map(el => { return Array.apply(null, { length: width }).map(element => { return value; }); }); return arr; }; console.log(fillArray(cols, rows, val));
Output
And the output in the console will be −
[ [ 'Example', 'Example', 'Example', 'Example', 'Example' ], [ 'Example', 'Example', 'Example', 'Example', 'Example' ], [ 'Example', 'Example', 'Example', 'Example', 'Example' ], [ 'Example', 'Example', 'Example', 'Example', 'Example' ] ]
Advertisements