Last updated: Mar 1, 2024
Reading timeยท4 min
To create an array with N elements containing the same value:
Array()
constructor to create an array of N elements.fill()
method to fill the array with a specific value.fill()
method changes all elements in the array to the supplied value.const arr = Array(3).fill('a'); console.log(arr); // ๐๏ธ ['a', 'a', 'a']
Array()
constructor, to create an array containing 3 empty elements.// ๐๏ธ [ <3 empty items> ] console.log(Array(3));
We used the Array.fill() method to fill the array with a specific value.
// ๐๏ธ [ 'abc', 'abc', 'abc' ] console.log(Array(3).fill('abc'));
The method takes a value and uses it to replace all array elements.
Alternatively, you can use the Array.from()
method instead of the Array()
constructor.
const arr = Array.from({length: 3}).fill('a'); console.log(arr); // ๐๏ธ ['a', 'a', 'a']
We passed the desired array length as an argument to the Array.from() method.
Array.from
method is a little more explicit and easier to read than instantiating the Array
constructor.When creating an array of N non-primitive elements with the same value, use the
Array.from()
method.
const arr = Array.from({length: 3}, () => { return {name: 'Bobby Hadz'}; }); // [ // { name: 'Bobby Hadz' }, // { name: 'Bobby Hadz' }, // { name: 'Bobby Hadz' } // ] console.log(arr);
Creating an array of non-primitive values is a bit trickier because we have to ensure that the objects in the array don't have the same reference.
If the objects are stored at the same location in memory, once one object gets updated, they all get updated.
Instead, we passed a map()
function as the second argument to the
Array.from()
method.
On each call of the map
function, we return an object.
If you update one object, the changes won't be reflected in the object objects because they are all stored in different locations in memory.
const arr = Array.from({length: 3}, () => { return {name: 'Bobby Hadz'}; }); // [ // { name: 'Bobby Hadz' }, // { name: 'Bobby Hadz' }, // { name: 'Bobby Hadz' } // ] console.log(arr); arr[0].name = 'new'; // [ { name: 'new' }, { name: 'Bobby Hadz' }, { name: 'Bobby Hadz' } ] console.log(arr);
Updating the name
property of the first object didn't update the property in
the other objects.
The same approach can be used to create a two-dimensional array with N elements, same value.
const arr = Array.from({length: 2}, () => Array.from({length: 3}, () => { return {name: 'Bobby Hadz'}; }), ); // [ // [ // { name: 'Bobby Hadz' }, // { name: 'Bobby Hadz' }, // { name: 'Bobby Hadz' } // ], // [ // { name: 'Bobby Hadz' }, // { name: 'Bobby Hadz' }, // { name: 'Bobby Hadz' } // ] // ] console.log(arr);
Notice that we used the Array.from()
method twice.
The outer call to the Array.from()
method determines the length of the outer
array.
The nested call to Array.from()
determines the length of each nested array.
You can use the same approach if you need to create an array by repeating multiple values N times.
const arr = Array(3).fill(['a', 'b', 'c']).flat(); // [ // 'a', 'b', 'c', // 'a', 'b', 'c', // 'a', 'b', 'c' // ] console.log(arr);
We passed an array of values to the Array.fill()
method and then used the
Array.flat()
method to flatten the array.
You can also pass a map
function as the second argument to the Array.from()
method when working with primitives.
const arr = Array.from({length: 5}, () => { return 'a'; }); // ๐๏ธ [ 'a', 'a', 'a', 'a', 'a' ] console.log(arr);
The code sample creates an array of 5
elements with the value of a
.
You can also explicitly chain a call to the Array.map()
function on the output
of the Array.from()
method.
const arr = Array.from(Array(5)).map(() => { return 'a'; }); // ๐๏ธ [ 'a', 'a', 'a', 'a', 'a' ] console.log(arr);
The Array.map()
function gets called for each element in the array.
Alternatively, you can use a for
loop.
for
loopThis is a three-step process:
for
loop to iterate N times.const arr = []; const total = 3; for (let i = 0; i < total; i++) { arr.push('a'); } console.log(arr); // ๐๏ธ ['a', 'a', 'a']
We declared a new arr
variable and initialized it to an empty array.
We used a for
loop to iterate N times and on each iteration, we pushed the
value into the new array.
Using a for
loop is a bit more verbose, but many developers are familiar with
how loops work.
while
loopYou can also use a while
loop to create an array of N elements with the same
value.
let total = 3; const arr = []; while (total--) { arr.push('a'); } console.log(arr); // ๐๏ธ [ 'a', 'a', 'a' ]
On each iteration of the while
loop, we decrement the total
variable until
it gets set to 0
.
Zero is a falsy value in JavaScript, so once 0
is reached, the loop exits.
You can learn more about the related topics by checking out the following tutorials: