How To Create An Array With the Same Elements Repeated Multiple Times in JavaScript – Definitive Guide

To create an array with the same element repeated multiple times in JavaScript, you can use the Array() constructor or the Array.from() method.

This tutorial teaches the different methods and when it is appropriate to use each method.

Using the Array() constructor

The Array() constructor is a global method that creates a new array instance.

  • Accepts a single integer argument that specifies the length of the array,
  • Creates an array filled with elements passed.

Use this method when you want to create an array directly from a single item instead of creating from iterable or applying a function to the items before adding it to the array.

Code

In the following example,

  • the Array() constructor is called with an argument of 5, which creates an array with a length of 5.
  • Then fill() method is then used to fill all the elements of the array with the value “foo”. This creates an array with 5 “foo” elements.
// Create an array of 5 "foo" elements

 var arr = Array(5).fill("foo");

 console.log(arr); // ["foo", "foo", "foo", "foo", "foo"]`

Using Array.from() method

The Array.from() method is a global method that creates a new array instance from an array-like or iterable object.

It accepts two arguments.

  • The array-like or iterable object to create the array from
  • A map function that specifies the value to be inserted into each element of the array. It returns a new array instance that contains the elements specified by the map function.

Use this method when you want to create an array from an array-like or iterable object, and fill it with a specific value. Also, when you want to perform additional operations on each element of the array before adding them to the new array.

Code

In the following example,

  • The Array.from() method is called with an object that has a length property of 5, and a map function that returns “foo” for each element of the array.
  • This creates an array of 5 “foo” elements.
// Create an array of 5 "foo" elements

var arr = Array.from({length: 5}, () => "foo"); 

console.log(arr); // ["foo", "foo", "foo", "foo", "foo"]`

Additional Resources

Leave a Comment