How to fill an Array in JavaScript? [SOLVED]


Written by - Olorunfemi Akinlua
Reviewed by - Deepak Prasad

Introduction

Are you looking to fill an array with a specific value in JavaScript? The fill method is a handy tool that allows you to do just that.

In this article, we will discuss how to use the fill method to fill an array with a specific value. We will also cover some additional features of the fill method, such as the ability to specify a start and end index for the fill, and how to use the fill method with typed arrays. By the end of this article, you should have a good understanding of how to use the fill method to manipulate arrays in your code.

So let's get started and learn how to use the fill method in JavaScript!

 

Method-1: Using the fill() method

In JavaScript, the fill() method is used to fill the elements of an array with a static value. This method modifies the original array, filling all of its elements with the static value provided as an argument. For example, we can make an array with different element values filled with a specific value (say, 0).

let arr = [1, 2, 3, 4];

arr.fill(0);

console.log(arr);

Output

[ 0, 0, 0, 0 ]

The fill() method is often used to initialize an array with a default value, or to quickly clear an array by filling it with null or undefined values. It can be called on any array-like object, and it accepts an optional second and third argument which specify the start and end index for filling the array. The fill() method returns the modified array.

Here are some more advanced examples of using the fill() method in JavaScript:

let arr = [1, 2, 3, 4];
arr.fill(0, 1, 3);

console.log(arr);

let arr1 = [1, 2, 3, 4];
arr1.fill(undefined);

console.log(arr1);

Output

[ 1, 0, 0, 4 ]
[ undefined, undefined, undefined, undefined ]

In the above example, we fill the array with a static value, starting at index 1 and ending at index 3. Then, the next operation fills the entire array with undefined values.

 

Method-2: Using the fill method with typed arrays

The fill method can be used with typed arrays, which are arrays with a fixed number of elements of a specific data type, such as Int8Array or Uint16Array.

To use the fill method with a typed array, you can call the fill method on the typed array and pass in the value you want to fill the array with as an argument. The fill method will fill the entire typed array with the specified value.

Here's an example of using the fill method with a Uint8Array typed array:

let arr = new Uint8Array(4);
arr.fill(255);

console.log(arr);

Output

Uint8Array(4) [ 255, 255, 255, 255 ]

In this example, we create a new Uint8Array typed array with 4 elements and use the fill method to fill the array with the value 255. The fill method fills the entire array with the value 255, and the output is [255, 255, 255, 255].

You can also use the fill method with a typed array to fill a specific range of elements within the array. To do this, you can pass in a start index and an end index as additional arguments to the fill method. The fill method will fill the elements within the specified range with the specified value.

Here's an example of using the fill method with a start and end index:

let arr = new Uint8Array([2, 2, 3, 43, 5]);
arr.fill(255, 1, 3);

console.log(arr);

Output

Uint8Array(5) [ 2, 255, 255, 43, 5 ]

In this example, we create a new Uint8Array typed array with the values 2, 2, 3, 43, and 5. We then use the fill method to fill the elements at indices 1 and 2 with the value 255. The fill method fills the specified range of elements with the value 255, and the output is Uint8Array(5) [ 2, 255, 255, 43, 5 ].

 

Method-3: Using push method

Instead of using the fill method, we can make use of the push method which appends new elements to the end of an array, and returns the new length of the array. Therefore, we can make use of the for loop over a pre-defined number of iterations (length of the array) and push the filler element at every iteration.

Here is an example of how to use the push metho alongside the for loop to fill arrays.

function filler(value, len) {
    const array = [];

    for (let i = 0; i < len; i++) {
        array.push(value);
    }

    return array;
}

const arr = filler("wow", 4);

console.log(arr);

Output

[ 'wow', 'wow', 'wow', 'wow' ]

In the above code, we define a function called filler that takes two arguments: value and len. Within the function, we make use a for loop to iterate len times, and on each iteration it pushes the value of value into an array called array. After the for loop has completed, the function returns the array with len elements, all of which have the value of value.

 

Method-4: Using the from method

Another approach to fill arrays is using the from method which creates an array from an iterable object. Before, we go further, the from() method syntax goes thus

Array.from(object, mapFn, thisValue)
  • object — An iterable object to convert to an array.
  • mapFn — A mapping function to call on every element of the array.
  • thisValue — Value of 'this' used to invoke the mapFn.

Now, for us to carry out an array fill operation, we will pass an object with length property and the intended value, and then pass anonymous function that will return the value we want filled.

Here is an example of how to make use of the from() method to fill an array.

let arr = Array.from(
    {
        length: 7,
    },
    () => "wow"
);
console.log(arr);

Output

[
  'wow', 'wow',
  'wow', 'wow',
  'wow', 'wow',
  'wow'
]

In the above code, the Array.from() method takes two arguments: the first is an iterable object, and the second is a map function that allows you to transform the elements as they are being added to the new array.

In this case, the iterable object is an object with a length property set to 7. This object does not have a Symbol.iterator property, so the Array.from() method will not actually iterate over the object's elements. Instead, it will create an array with 7 elements, all of which will be the result of calling the map function.

The map function is a function that takes no arguments and returns the string "wow". This function will be called 7 times, once for each element of the new array, and the result of each call will be added to the array as an element.

 

Summary

To fill an array, we can make use of the fill method which can be helpful with typical and typed arrays. In addition, we can specify the section of the array we want to fill.

 

References

Array.prototype.fill() - JavaScript | MDN (mozilla.org)
Array.from() - JavaScript | MDN (mozilla.org)
Array.prototype.push() - JavaScript | MDN (mozilla.org)

 

Views: 1

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on LinkedIn.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment