Sometimes, we may want to create a JavaScript array with the same repeated repeated multiple times as its content.
In this article, we’ll look at how to create a JavaScript array with the same element repeated multiple times.
For Loop and Array.prototype.push
We can use the for loop to run the push
method to add an item to an array multiple times.
For instance, we can write:
const fillArray = (value, len) => {
const arr = [];
for (let i = 0; i < len; i++) {
arr.push(value);
}
return arr;
}
const arr = fillArray(2, 5)
console.log(arr)
We create the fillArray
function that has the value
and len
parameters.
value
is the value we want to fill in the array.
len
is the length of the returned array.
arr
is the array with the repeated values.
After creating arr
, we use the for loop to call push
len
times to push the same value
to arr
.
And after we call it, we get an array returned.
So arr
is [2, 2, 2, 2, 2]
since we fill the array with value 2 five times.
Array.prototype.fill
Another way to fill an array with a value repeatedly is to use the fill
method.
It takes an argument with the value to fill.
We can combine this with the Array
constructor to create an array with given length.
For instance, we can write:
const arr = Array(5).fill(2)
console.log(arr)
We call Array(5)
to create an empty array with 5 empty slots.
Then we call fill
with 2 to fill all the empty slots with 2.
And so arr
is the same as the previous example.
Spread Operator and Array.prototype.map
Another way to create an array with a value repeated throughout the array is to use the spread operator and the map
method.
For instance, we can write:
const arr = [...Array(5)].map((_, i) => 2)
console.log(arr)
We create an array with 5 empty slots with Array
and spread it into the array.
And then we call map
to return 2 in each slot.
And finally, we get the same result as before for arr
.
Array.from
Array.from
is another method that we can use to create an array filled with the same value throughout the array.
It works by creating an empty array and map the empty slots to the value we want.
For example, we can write:
const arr = Array.from({
length: 5
}, i => 2)
console.log(arr)
We create an empty array with length 5 with Array.from
.
Then in the 2nd argument, we pass in a callback to map the empty values to 2.
So we get the same result as before.
Lodash
We can use the times
and constant
Lodash methods to return an array that repeats a value throughout.
To do this, we write:
const arr = _.times(5, _.constant(2));
console.log(arr)
The constant
method ensures that we repeat the element.
And so arr
is the same value as the other examples.
We can do this more easily with the fill
method.
To do this, we write:
const arr = _.fill(Array(5), 2);
console.log(arr)
We pass in the empty array into the first argument and the value to repeat in the 2nd argument.
Conclusion
We can use JavaScript array methods or Lodash methods to fill an array with the same value throughout.