How to Fill A JavaScript Array
-
Use
Array.prototype.fill()
to Fill an Array in JavaScript -
Use
Array.prototype.map()
to Fill an Array in JavaScript -
Use the
Array.from()
Method to Fill an Array in JavaScript -
Use the
apply()
Method to Fill an Array in JavaScript -
Use the
loop
Statement to Fill an Array in JavaScript
In JavaScript, the Array.prototype.fill()
method works successively to fill a certain ranged array. However, the operation can get slow for many elements depending on browsers.
More or less, most of the ways that fill an array face this slow pace for a larger number of elements. But some methods work better in the case of fast comparative operation.
Here, we will see the application of the methods fill()
, map()
, from()
, apply()
, and the basic loop
statement to fill an array. Let’s jump to the code lines.
Use Array.prototype.fill()
to Fill an Array in JavaScript
This method requires one line of code to initialize the array element. And the default function of the fill()
method does its job of filling an array.
Code Snippet:
var a = new Array(5).fill(1);
console.log(a);
Output:
Use Array.prototype.map()
to Fill an Array in JavaScript
Here, we will use a spread operator to expand the elements of the array and later apply the map()
on each element to fill them with a value. The code fence explains better.
Code Snippet:
var a = [...new Array(5)].map(x => 2);
console.log(a);
Output:
Use the Array.from()
Method to Fill an Array in JavaScript
In this case, we will use the Array.from()
method that will take an array instance defining its range, and also, there will be a function set that will initialize the element’s value described in the lambda function scope. Let’s check the code block.
Code Snippet:
var a = Array.from(Array(5), () => 3);
console.log(a);
Output:
Use the apply()
Method to Fill an Array in JavaScript
We will use the apply()
method to hold all the elements of an array up to a certain range. And later, we will use the map()
function to assign value to each element.
var a = Array.apply(null, Array(5)).map(Number.prototype.valueOf, 4);
console.log(a);
Output:
Use the loop
Statement to Fill an Array in JavaScript
Here, we will use a basic loop to traverse the elements of an array up to the specified range and then initialize the values.
Code Snippet:
var a = new Array(5);
for (var i = 0; i < 5; i++) {
a[i] = 5;
}
console.log(a);
Output:
Related Article - JavaScript Array
- How to Check if Array Contains Value in JavaScript
- How to Create Array of Specific Length in JavaScript
- How to Convert Array to String in JavaScript
- How to Remove First Element From an Array in JavaScript
- How to Search Objects From an Array in JavaScript
- How to Convert Arguments to an Array in JavaScript