Create an Array with N elements, same Value in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 1, 2024
4 min

banner

# Create an Array with N elements, same Value in JavaScript

To create an array with N elements containing the same value:

  1. Use the Array() constructor to create an array of N elements.
  2. Use the fill() method to fill the array with a specific value.
  3. The fill() method changes all elements in the array to the supplied value.
index.js
const arr = Array(3).fill('a'); console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'a', 'a']

create array with n elements same value

The code for this article is available on GitHub
We first used the Array() constructor, to create an array containing 3 empty elements.
index.js
// ๐Ÿ‘‡๏ธ [ <3 empty items> ] console.log(Array(3));

We used the Array.fill() method to fill the array with a specific value.

index.js
// ๐Ÿ‘‡๏ธ [ 'abc', 'abc', 'abc' ] console.log(Array(3).fill('abc'));

The method takes a value and uses it to replace all array elements.

# Using the Array.from() method instead

Alternatively, you can use the Array.from() method instead of the Array() constructor.

index.js
const arr = Array.from({length: 3}).fill('a'); console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'a', 'a']

using array from method instead

The code for this article is available on GitHub

We passed the desired array length as an argument to the Array.from() method.

Using the Array.from method is a little more explicit and easier to read than instantiating the Array constructor.

# Create an Array of N non-primitive elements with the same value

When creating an array of N non-primitive elements with the same value, use the Array.from() method.

index.js
const arr = Array.from({length: 3}, () => { return {name: 'Bobby Hadz'}; }); // [ // { name: 'Bobby Hadz' }, // { name: 'Bobby Hadz' }, // { name: 'Bobby Hadz' } // ] console.log(arr);

create array of n non primitive elements with same value

The code for this article is available on GitHub

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.

index.js
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.

# Creating a two-dimensional array with N elements, same value

The same approach can be used to create a two-dimensional array with N elements, same value.

index.js
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);
The code for this article is available on GitHub

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.

# Repeating multiple values N times

You can use the same approach if you need to create an array by repeating multiple values N times.

index.js
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.

index.js
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.

index.js
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.

# Create an Array with N elements, same Value using a for loop

This is a three-step process:

  1. Declare a variable that stores an empty array.
  2. Use a for loop to iterate N times.
  3. On each iteration, push the value into the array.
index.js
const arr = []; const total = 3; for (let i = 0; i < total; i++) { arr.push('a'); } console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'a', 'a']
The code for this article is available on GitHub

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.

# Create an Array with N elements, same Value using a while loop

You can also use a while loop to create an array of N elements with the same value.

index.js
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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev