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:
let array = []
for (let index = 0; index < 10; index++) {
array.push(1)
}
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.
const array = Array(10).fill(1)
console.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:
const array = [1, 2, 3, 4]
array.fill(5, 2, 4)
console.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:
const array1 = Array.from({ length: 10 }, () => 1)
console.log(array1) // [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
const array2 = Array.from(Array(10), () => 1)
console.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:
const array = [...Array(10)].map(() => 1)
console.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:
const array1 = Array.from({ length: 10 }, (value, index) => index + 1)
console.log(array1) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const array2 = [...Array(10)].map((value, index) => index + 1)
console.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:
const array = Array.from({ length: 5 }, (value, index) => {
return { id: index + 1 }
})
console.log(array) // [{"id":1},{"id":2},{"id":3},{"id":4},{"id":5}]
If you know any other methods, please do comment them below.
Top comments (0)