Open In App

JavaScript- Creating a Zero-Filled JS Array

Last Updated : 27 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Using Array.prototype.fill() Method- Basic and Mostly Used

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.

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.

Using Apply() and Map() Method

We have used 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.

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

Output
[ 0, 0, 0, 0, 0 ]

Using Array.from() Method

This method is used to create a new,shallow-copied array from an array-like or iterable object. The 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 ]

Using for loop – Easy and Efficient Approach

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.

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

Output
[ 0, 0, 0, 0, 0 ]

Using Lodash _.fill() Method – Third Party

The Lodash _.fill() method is used to fill a set of values into the array in a given range.

JavaScript
const len = 10; // Set the desired length of the array
const res = _.fill(Array(len), 0);
console.log(res);

Output:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]


Similar Reads