This post will discuss how to initialize a nested array with zeros in JavaScript.

To initialize a nested array with zeros, we have to create an array of a given size and fill each element with another array of zeros. Here are some of the ways to do it in JavaScript:

1. Using Array.fill() function

A simple way to initialize a nested array with zeros is using the Array() constructor with the Array.fill() function. The Array() constructor takes a number as an argument and create an array of that length with empty elements. The fill() function fills all or part of an array with a specified value. We can use them to create and fill a nested array with zeros creating an array of sub-arrays using the Array() constructor and then filling each sub-array with zero using the fill() function. Here’s an example:

Download  Run Code

 
In the above example, the Array() constructor creates an array of length rows and the fill() function fills the array with empty values. Then map() function creates a new array of length cols for each of the row, and filled with zeros using the fill() function. Note we can eliminate the need for the map() function by creating the array and filling each element with another array of zeros in a single call. Here’s an example:

Download  Run Code

2. Using Array.from() function

We can also use the Array.from() function that can create an array from an iterable. It takes a callback function as a second argument and map each element of the source object to a new value. To create and fill a nested array with zero value, we can pass a function that returns a sub-array of zeros as the second argument.

Download  Run Code

3. Using nested for loops

A straightforward and intuitive way to create and fill a nested array with zeros is using loops. We can use two nested for loops to iterate over the rows and columns of the array and assign zero to each element. Here’s an example:

Download  Run Code

 
In this example, arr is a nested array with three rows and four columns, with all elements initialized with the value 0. Unlike the previously discussed approaches, which require ES6 support or a polyfill for older browsers, this function is compatible with older browsers. However, it may not be very efficient or elegant for large arrays.

That’s all about initializing a nested array with zeros in JavaScript.