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
const initialize_2D_Array = (w, h, val = null) =>
Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val));
console.log(initialize_2D_Array(2, 2, 0));
console.log(initialize_2D_Array(3, 3, 3));
Sample Output:
[[0,0],[0,0]] [[3,3,3],[3,3,3],[3,3,3]]
Pictorial Presentation:
Flowchart:

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.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join