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.


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));


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' ]

Updated on: 20-Nov-2020


Kickstart Your Career

Get certified by completing the course

Get Started