Create an array with same element repeated multiple times

Create an array with same element repeated multiple times

In Python, where [2] is a list, the following code gives this 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?
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; };

Solutions/Answers:

Solution 1:

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++) {
    arr.push(value);
  }
  return arr;
}

Solution 2:

In ES6 using Array fill() method

Array(5).fill(2)
//=> [2, 2, 2, 2, 2]

Solution 3:

>>> Array.apply(null, Array(10)).map(function(){return 5})
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
>>> //Or in ES6
>>> [...Array(10)].map((_, i) => 5)
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]

Solution 4:

you can try:

Array(6).join('a').split(''); // returns ['a','a','a','a','a'] (5 times)

Update (01/06/2018):

Related:  What does \u003C mean?

Now you can have a set of characters repeating.

new Array(5).fill('a'); // give the same result as above;
// or
Array.from({ length: 5 }).fill('a')

Note: Check more about fill(…) and from(…) for compatibility and browser support.

Solution 5:

Array.from({length:5}, i => 1) // [1, 1, 1, 1, 1]

or create array with increasing value

Array.from({length:5}, (e, i)=>i) // [0, 1, 2, 3, 4]

Solution 6:

In lodash it’s not so bad:

_.flatten(_.times(5, function () { return [2]; }));
// [2, 2, 2, 2, 2]

EDIT: Even better:

_.times(5, _.constant(2));
// [2, 2, 2, 2, 2]

EDIT: Even better:

_.fill(Array(5), 2);