How to form a two-dimensional array with given width (columns) and height (rows) in JavaScript ?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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' ]
]
raja
Published on 20-Nov-2020 09:59:34
Advertisements