w3resource

JavaScript: Initialize a two dimension array of given width and height and value

JavaScript fundamental (ES6 Syntax): Exercise-53 with Solution

Write a JavaScript program to initialize a two-dimensional array of given size and value.

  • Use Array.from() and Array.prototype.map() to generate h rows where each is a new array of size w.
  • Use Array.prototype.fill() to initialize all items with value val.
  • Omit the last argument, val, to use a default value of null.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2
// Define a function 'initialize_2D_Array' to create a 2D array with a specified width, height, and default value.
const initialize_2D_Array = (w, h, val = null) =>
  // Create an array with the specified height and map each element to an array with the specified width filled with the default value.
  Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val));

// Test cases
console.log(initialize_2D_Array(2, 2, 0)); // Output: [ [ 0, 0 ], [ 0, 0 ] ]
console.log(initialize_2D_Array(3, 3, 3)); // Output: [ [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ] ]

Output:

[[0,0],[0,0]]
[[3,3,3],[3,3,3],[3,3,3]]

Visual Presentation:

JavaScript Fundamental: Initialize a two dimension array of given width and height and value
JavaScript Fundamental: Initialize a two dimension array of given width and height and value

Flowchart:

flowchart: Initialize a two dimension array of given width and height and value

Live Demo:

See the Pen javascript-basic-exercise-1-53 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to group the elements of an given array based on the given function.
Next: Write a JavaScript program to initialize an array containing the numbers in the specified range where start and end are inclusive with their common difference step.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-53.php