How to Fill A JavaScript Array

Anika Tabassum Era Feb 15, 2024
  1. Use Array.prototype.fill() to Fill an Array in JavaScript
  2. Use Array.prototype.map() to Fill an Array in JavaScript
  3. Use the Array.from() Method to Fill an Array in JavaScript
  4. Use the apply() Method to Fill an Array in JavaScript
  5. Use the loop Statement to Fill an Array in JavaScript
How to Fill A JavaScript Array

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.fill() to Fill an Array

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 Array.prototype.map() to Fill an Array

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 Array.from() Method to Fill an Array

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 apply() Method to fill an Array

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:

Use loop Statement to Fill an Array

Anika Tabassum Era avatar Anika Tabassum Era avatar

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

LinkedIn Facebook

Related Article - JavaScript Array