Creating a Zero-Filled Array in JavaScript
Last Updated :
30 Jan, 2024
A zero-filled array is an array whose value at each index is zero.
Below are the methods used for creating a Zero-Filled Array in JavaScript:
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: The following code snippet demonstrates the fill() method with 0 value.
Javascript
const arr = new Array(5).fill(0);
console.log(arr);
|
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.
In the below example, we use the 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);
|
This method is used to create a new,shallow-copied array from an array-like or iterable object.
Syntax:
Array.from(arrayLike, (element) => { /* ... */ } )
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);
|
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);
|
the
JavaScript for loop is used to iterate the elements for a fixed number of times. JavaScript for loop is used if the number of the iteration is known.
Syntax:
for (statement 1 ; statement 2 ; statement 3){
code here...
}
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);
|
Method 5: Using Lodash _.fill() Method
Lodash _.fill() method is used to fill a set of values into the array in a given range.
Syntax:
_.fill(array, value, startIndex, endIndex);
Example: This example shows the use of the Lodash _.fill() method.
Javascript
const arrayLength = 10;
const zeroFilledArray = _.fill(Array(arrayLength), 0);
console.log(zeroFilledArray);
|
Output:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Share your thoughts in the comments
Please Login to comment...