Create An Array Of n Elements With Same Value In JavaScript

You can create an array of n elements with same value, using any of the following methods –

  1. Use Array(n).fill(value)
  2. Use Array.from(new Array(n), () => value);
  3. Use a for loop

Let’s discuss each of these methods in detail.

Create An Array Of n Elements With Same Value

create an array of n elements with same value in javascript

1) Use Array(n).fill(value)

The fill() method fills the elements of an array with a static value. It is a static method that is invoked on the Array class, and not on individual arrays.

This method takes in two arguments –

  • the first argument is the static value that is to be filled in all the elements of the array
  • the second argument is optional, and it represents the start index (default is 0), up to which the static value is to be filled.

If the second argument is not provided, then all the elements of the array from index 0 to its last index will be filled.

After filling, the length of the array won’t change.

Here is the complete code –

let n = 5;

let value = 10;

console.log(Array(n).fill(value)); // Output – > Array (5) {10, 10, 10, 10, 10}

2) Use Array.from(new Array(n), () => value);

Array.from() creates a new shallow-copied Array instance from an array-like or iterable object.

The first argument of Array.from is the array-like object or iterable, and the second argument is a map function that is called on every element of the array-like to create the new array, with the same length as the input.

In our case, we do not need any mapping function, so we’ll pass in a function that returns the static value.

This means that every element of the new array will be set to the static value.

Here is the complete code –

let n = 5;

let value = 10;

console.log(Array.from(new Array(n), () => value)); // Output – > Array (5) {10, 10, 10, 10, 10}

3) Use A for Loop

This is the most basic method to create an array with static values. We’ll use a for loop and set each element of the array to the static value one by one.

Here is the complete code –

let n = 5;

let value = 10;

let arr = [];

for(let i=0; i<n; i++) {

  arr.push(value);

}

console.log(arr); // Output – > Array (5) {10, 10, 10, 10, 10}

These were some of the methods that you can use to create an array of n elements with same value.

You can choose any of these methods based on your requirement and convenience.

Leave a Reply