In JavaScript, if you want to fill an array with zeros or with some other value such as a string or object, you can use the Array.fill()
method. The Array.fill()
method fills each array slot with the same value that you have passed to it.
Let’s say we want to create an array of size 5, where each array slot is filled with 0. We can do it in the following way:
// Create an array of size 5 const arr = new Array(5); // Fill each array slot with 0 arr.fill(0); console.log(arr); // Output: [0, 0, 0, 0, 0]
You can also create the above array in just a single line by first creating the array with empty slots and then filling it with zeros.
This is how you can do it:
// Create an array of size 5 and fill with zeros const arr = new Array(5).fill(0); console.log(arr); // Output: [0, 0, 0, 0, 0]
Create a Two Dimensional Array of Zeros
Just like a 1-dimensional array, you can also create a 2-dimensional array of zeros. A 2-dimensional array is basically an array of arrays where the inner arrays contain the actual data.
Example of a 3×3 two-dimensional array filled with zeros:
// A 3X3 two-dimensional array const arr = [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ];
This is how you can create it using JavaScript:
const rows = 3, cols = 3; // Create a 1-D array of 3 items const arr = new Array(rows); for(let i=0;i<rows;i++){ // Set each array item to an array arr[i] = new Array(cols); // Fill each array item with zero arr[i].fill(0); } // Print the array console.log(arr);
Output:
[ [0, 0, 0], [0, 0, 0], [0, 0, 0] ]
You can also create the above two-dimensional array and fill it with zeros in a single line using the Array.map()
method in combination with the Array()
constructor and the Array.fill()
method.
See the below example:
const rows = 3, cols = 3; // Create the 2-D array and fill it with zeros const arr = new Array(rows).fill(0).map(row=>new Array(cols).fill(0)); // Print the array console.log(arr);
Output:
[ [0, 0, 0], [0, 0, 0], [0, 0, 0] ]