Monday, September 23, 2024
Google search engine
HomeLanguagesJavascriptCreating a Zero-Filled Array in JavaScript

Creating a Zero-Filled Array in JavaScript

In this article, we will create a zero-filled array in JavaScript. A zero-filled array is an array whose value at each index is zero. For this, we have a few methods such as we can use:

  • Array fill() method 
  • Array.from() method
  • Array constructors can also be used to create a zero-filled array.
  • Array using for loop

Method 1: Array.prototype.fill.

The fill() method is used to change the elements of the array to a static value from the initial index (by default 0) to the end index (by default array.length). The modified array is returned.

Syntax:

fill(value, start, end)

Example 1: The following code snippet demonstrates the fill() method with 0 value.

Javascript




const arr = new Array(5).fill(0);
console.log(arr);


Output:

[0, 0, 0, 0, 0]

Array constructor takes the size of an array as a parameter if we pass one argument into it. fill() method takes the value we want to fill in the array.

Note: JavaScript fill() method is available since ES6.

Method 2: Using Apply() and Map().

In the below example, we use apply() method to create an array of 5 elements that can be filled with the map() method. In the map() method, we pass in a callback that returns 0 to fill all the indexes with zeros.

Example:  Array.apply() method is used to create an empty array in which we can use the map() method to store each element as key-value pair.

Javascript




const arr = Array.apply(null, Array(5)).map(() => 0);
console.log(arr);


Output:

[0, 0, 0, 0, 0]

Method 3: Using Array.from().

This method is used to create a new,shallow-copied array from an array-like or iterable object.

Syntax:

Array.from(arrayLike, (element) => { /* ... */ } )

Example: In the below example, Array.from() is called which lets us map an empty array of size 5 to an array with some elements inside. The second argument is a callback that returns 0 which is used to fill the array.

Javascript




const arr = Array.from(Array(5), () => 0)
console.log(arr);


Output:

[0, 0, 0, 0, 0]

The same result can be obtained by passing an object with the length property using the Array.from() method.

Javascript




const arr = Array.from({
    length: 5
}, () => 0)
console.log(arr);


Output:

[0, 0, 0, 0, 0]

Method 4: Using for loop:

Example: In this example, we will use the for loop for creating a zero-filled array.

Javascript




let zeroArr = []
for (i = 0; i < 5; i++) {
    zeroArr[i] = 0;
}
console.log(zeroArr);


Output:

[ 0, 0, 0, 0, 0 ]

RELATED ARTICLES

Most Popular

Recent Comments