Categories
JavaScript Answers

How to Fill Arrays with Data with JavaScript?

Spread the love

With ES6 or later, we can fill arrays with an array with new data with the fill method. The fill method takes up to 3 arguments. The first is the value we want to add to the array.

The second optional argument is the start index of which we want to start filling data.

The default value of the second argument is 0. The third argument is an optional one that lets us specify the end index of to fill the array entry up to.

The default value for the third argument is the length of the array. Note that the end index itself is excluded from the filling so it won’t overflow when we call the fill method.

The fill the method returns a new array with the new values filled in. All existing values that were filled will replace any existing values that were in the original array.

For example, we can use it in the following way:

let arr = [1, 2, 3, 4, 5, 6];
arr = arr.fill(8)
console.log(arr);

Then we get the following output from the console.log :

[8, 8, 8, 8, 8, 8]

We can also change the index of the fill method to specify the fill boundary. For example, we can write:

let arr = [1, 2, 3, 4, 5, 6];
arr = arr.fill(8, 3, 5)
console.log(arr);

Then we get:

[1, 2, 3, 8, 8, 6]

from the console.log . If we specify an end index that’s over the length of the original array, then it’ll replace the values up to the original array up to the last position of the original array. For example, if we have:

let arr = [1, 2, 3, 4, 5, 6];
arr = arr.fill(8, 3, 10)
console.log(arr);

Then we get:

[1, 2, 3, 8, 8, 8]

We can also use negative indexes to specify the fill boundary with the fill method. The last position of the array would be -1, the second last would be -2, and so on. So we can call fill with negative indexes like the following:

let arr = [1, 2, 3, 4, 5, 6];
arr = arr.fill(8, -4, -1)
console.log(arr);

Then we get:

[1, 2, 8, 8, 8, 6]

since the third argument doesn’t include the last index. If we want to fill the last element as well with the new value, then we just omit the last argument like in the following code:

let arr = [1, 2, 3, 4, 5, 6];
arr = arr.fill(8, -4)
console.log(arr);

We get [1, 2, 8, 8, 8, 8] when we run the code above. If the second argument’s value is bigger than the third argument, then no fill operation will take place and the original array is returned. For example, if we have:

let arr = [1, 2, 3, 4, 5, 6];
arr = arr.fill(8, 4, 1)
console.log(arr);

Then we get back [1, 2, 3, 4, 5, 6] which is the original array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *