- 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
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' ] ]
- Related Articles
- Creating a two-dimensional array with given width and height in JavaScript
- Get the width and height of a three-dimensional array
- How to create a two dimensional array in JavaScript?
- Display a two-dimensional array with two different nested loops in matrix form PHP?
- How to layout table cells, rows, and columns with JavaScript?
- Split one-dimensional array into two-dimensional array JavaScript
- Transpose of a two-dimensional array - JavaScript
- How to multiply a matrix columns and rows with the same matrix rows and columns in R?
- How to split comma and semicolon separated string into a two-dimensional array in JavaScript ?
- How to declare a two-dimensional array in C#
- How to create a GridLayout with rows and columns in Java?
- How to get rows and columns of 2D array in Java?
- How to set the width of the rule between columns with JavaScript?
- How to get the Width and Height of the screen in JavaScript?
- How to find the inner height and inner width of a browser window in JavaScript?

Advertisements