Skip to content
javascript

How to fill an array in JavaScript with initial values

Nov 5, 2021Abhishek EH3 Min Read
How to fill an array in JavaScript with initial values

You will come across instances where you want to have an array with predefined values so that you can iterate over them. The very obvious way will be to create a for loop and initialize an array as shown below:

1let array = []
2
3for (let index = 0; index < 10; index++) {
4 array.push(1)
5}

We will see 3 other methods to fill an array in javascript without explicitly using a for loop.

Using Array.fill method

We can use the fill method provided by the Array object to populate the array with predefined values.

1const array = Array(10).fill(1)
2
3console.log(array) // [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

The Array(10) will create an empty (sparse) array of size 10.

The fill method accepts additional parameters, which can be used to fill only part of an array:

1const array = [1, 2, 3, 4]
2
3array.fill(5, 2, 4)
4
5console.log(array) //[1, 2, 5, 5]

The second argument is used to specify from which position to begin (inclusive) and the third argument says till where to fill (exclusive, maximum being array.length).

Using Array.from method

We can fill an array using Array.from method using 2 different ways:

1const array1 = Array.from({ length: 10 }, () => 1)
2console.log(array1) // [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
3
4const array2 = Array.from(Array(10), () => 1)
5console.log(array2) //[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

The first argument accepts an array or an iterable object and the second argument is a map function which should return the value to be filled.

Using spread operator and .map function

We can use a combination of spread operator and map function as well to fill an array:

1const array = [...Array(10)].map(() => 1)
2console.log(array) //[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

Here spreading and creating another array is necessary since Array(10).map(()=>1) will only create an empty (sparse) array.

Filling array with 1..n

If you need to fill an array with numbers starting from 1 to n (say 1 to 10), you can do that using one of the following code:

1const array1 = Array.from({ length: 10 }, (value, index) => index + 1)
2console.log(array1) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
3
4const array2 = [...Array(10)].map((value, index) => index + 1)
5console.log(array2) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Filling an array with objects

Not only numbers, you can fill an array with other type of values like string, object etc. If you need to create an array of objects, then you can do it as shown below:

1const array = Array.from({ length: 5 }, (value, index) => {
2 return { id: index + 1 }
3})
4console.log(array) // [{"id":1},{"id":2},{"id":3},{"id":4},{"id":5}]

If you know any other methods, please do comment them below.

Do follow me on twitter where I post developer insights more often!

© 2024 CodingDeft.Com