Curious2learn Curious2learn - 1 year ago 127
Javascript Question

Create an array with same element repeated multiple times in JavaScript

In Python, where

is a list, gives the output:

[2] * 5

# Outputs: [2,2,2,2,2]

Does there exist an easy way to do this with an array in JavaScript?

I wrote the following function to do it, but is there something shorter or better? Thank you.

var repeatelem = function(elem, n){
// returns an array with element elem repeated n times.
var arr = [];
for (var i=0; i<=n; i++) {
arr = arr.concat(elem);
return arr;

Answer Source

You can do it like this:

function fillArray(value, len) {
  if (len == 0) return [];
  var a = [value];
  while (a.length * 2 <= len) a = a.concat(a);
  if (a.length < len) a = a.concat(a.slice(0, len - a.length));
  return a;

It doubles the array in each iteration, so it can create a really large array with few iterations.

Note: You can also improve your function a lot by using push instead of concat, as concat will create a new array each iteration. Like this (shown just as an example of how you can work with arrays):

function fillArray(value, len) {
  var arr = [];
  for (var i = 0; i < len; i++) {
  return arr;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download