Form a Two-Dimensional Array 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' ]
]
Updated on: 2020-11-20T10:00:32+05:30

387 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements