In JavaScript, an array is a collection of elements that can be of any data type. Sometimes, it is necessary to fill an array with a specific value for a given number of times. For example, an array of length 10 needs to be filled with the value 0, or an array of length 5 needs to be filled with the value “Hello”.
Approach: There are several ways to fill an array with a given value in JavaScript.
- One of the most common ways is to use the Array.fill() method. This method modifies the original array and fills it with a given value for a specified number of times.
- Another approach is to use a for loop to iterate over the array and fill it with the desired value.
- Another way is to use the Array.push() method. This method adds one or more elements to the end of an array and returns the new length of the array. This method can be used to fill an array by repeatedly adding the same value to the end of the array.
- The spread operator can also be used to fill an array with a given value. The spread operator allows an iterable to expand in places where 0+ arguments are expected.
Example 1: Using Array.fill() method:
The Array.fill() method is used to fill an array with a specified value for a specified number of times. In this example, the Array.fill() method is used to fill an array of length 10 with the value 0.
Javascript
let myArray = new Array(10); myArray.fill(0); console.log(myArray); |
Output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Example 2: Using for loop:
In this example, a for loop is used to iterate over the array and fill it with the value “Hello”. The for loop starts at index 0 and goes until the end of the array, which is specified by the myArray.length property.
Javascript
let myArray = new Array(5); for (let i = 0; i < myArray.length; i++) { myArray[i] = "Hello" ; } console.log(myArray); |
Output: ["Hello", "Hello", "Hello", "Hello", "Hello"]
Example 3: Using Array.push() method:
In this example, the Array.push() method is used to add elements to the end of the array. The for loop is used to repeat the push method 10 times to add the value 0 to the array.
Javascript
let myArray = []; for (let i = 0; i < 10; i++) { myArray.push(0); } console.log(myArray); |
Output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Example 4: Using the spread operator:
In this example, the spread operator is used to expand the Array(5) which creates an array with 5 empty slots, and then the Array.map() method is used to fill all the empty slots with the value “Hello”
Javascript
let myArray = new Array(5); myArray = [...Array(5)].map(() => 'Hello' ); console.log(myArray); |
Output: ["Hello", "Hello", "Hello", "Hello", "Hello"]
Example 5: Using the Array.from():
Use the following syntax to fill the array of size n with 0 value. Use any value in place of 0.
Syntax:
Array.from({length: n}, ()=> 0 );
Javascript
let arr = Array.from({length: 5}, () => 0); console.log(arr.length); console.log(arr) |
Output:
5 [ 0, 0, 0, 0, 0 ]