Create a 2D array filled with specific value in JavaScript
This post will discuss how to create a 2D array pre-filled with a specified value in JavaScript.
To create a 2D array of fixed dimensions initialized with a specified value, you can use any of the following methods:
1. Using Array constructor
In JavaScript, 2D arrays can be easily created using the array constructor and the for-loop. To initialize it with the specific value, use fill() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const R = 3, C = 4; const val = 1; var arr = Array(R); for (var i = 0; i < R; i++) { arr[i] = Array(C).fill(val); } console.log(arr); /* Output: [ [ 1, 1, 1, 1 ], [ 1, 1, 1, 1 ], [ 1, 1, 1, 1 ] ] */ |
2. Using Array.from() function
The Array.from() method creates a new array instance from the specified array and optionally map each array element to a new value. This can be used as follows for creating a 2D array:
|
1 2 3 4 5 6 7 8 9 |
const R = 3, C = 4; const val = 1; var arr = Array.from({ length: R }, () => Array.from({ length: C }, () => val)); console.log(arr); /* Output: [ [ 1, 1, 1, 1 ], [ 1, 1, 1, 1 ], [ 1, 1, 1, 1 ] ] */ |
You can simplify this to the following code:
|
1 2 3 4 5 6 7 8 9 |
const R = 3, C = 4; const val = 1; var arr = Array.from(Array(R), () => Array(C).fill(val)); console.log(arr); /* Output: [ [ 1, 1, 1, 1 ], [ 1, 1, 1, 1 ], [ 1, 1, 1, 1 ] ] */ |
3. Using Array.prototype.map() function
Alternatively, you can directly call the map() function on the array, as shown below:
|
1 2 3 4 5 6 7 8 9 |
const R = 3, C = 4; const val = 1; var arr = Array(R).fill().map(() => Array(C).fill(val)); console.log(arr); /* Output: [ [ 1, 1, 1, 1 ], [ 1, 1, 1, 1 ], [ 1, 1, 1, 1 ] ] */ |
4. Using array literal notation
Finally, 2D arrays can also be created using the array literal notation. The following code example shows how to implement this using two loops:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const R = 3, C = 4; const val = 1; var arr = []; for (var i = 0; i < R; i++) { arr[i] = []; for (var j = 0; j < C; j++) { arr[i][j] = val; } } console.log(arr); |
That’s all about creating a 2D array filled with the specified value in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)