Sometimes, we want to create a 2D array of zeroes in JavaScript.
In this article, we’ll look at how to create a 2D array of zeroes in JavaScript.
How to create a 2D array of zeroes in JavaScript?
To create a 2D array of zeroes in JavaScript, we can use some array methods.
For instance, we write:
const zeroes = Array(3).fill().map(() => Array(3).fill(0));
console.log(zeroes)
to create an array with Array
to create an array with length 3.
Then we call fill
and map
to fill the empty slots and map them to arrays with 0’s in it.
Therefore, zeroes
is:
[
[
0,
0,
0
],
[
0,
0,
0
],
[
0,
0,
0
]
]
Conclusion
To create a 2D array of zeroes in JavaScript, we can use some array methods.