615

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;
};
2

25 Answers 25

1247

In ES6 using Array fill() method

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

9
  • 3
    Internet Explorer and Opera don't support it yet. Jan 19, 2016 at 16:30
  • 4
    Node.js <= 3 does not support this.
    – Junle Li
    Feb 26, 2016 at 20:22
  • 2
    There is an existing polyfill for those lacking support.
    – JohnnyQ
    Feb 27, 2018 at 3:03
  • 17
    @Michael You can do it with Array(5).fill([1,2,3]).flat(). Note that flat() is still very experimental and browser support is poor. Sep 16, 2018 at 16:12
  • 34
    Note that the argument to fill is evaluated once, so Array(9).fill(someMutable) creates nine references to someMutable in the array (mutating one mutates 'them all').
    – Carl Smith
    Jan 29, 2019 at 21:20
179
>>> Array.apply(null, Array(10)).map(function(){return 5})
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
>>> //Or in ES6
>>> Array.from({length: 10}, () => 5)
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
7
  • 12
    Silly question, but why new Array(10).map does not work?
    – blazkovicz
    Jul 10, 2015 at 8:39
  • 2
    blazkovicz, see zertosh's comment on this answer for the reason. Jul 14, 2015 at 18:24
  • 9
    With ES6, this can be "upgraded" to Array(...Array(10)).map(() => 5) with the spread operator or also to Array.from(Array(10)).map(() => 5) Oct 28, 2015 at 11:42
  • 10
    According to MDN, you can just like this: Array.from({length: 10}, () => 5); Dec 25, 2015 at 9:49
  • 5
    @blazkovicz Array(10) creates an array of lenght = 10 without any enumerable properties. .map only works on enumerable properties. The .apply method takes this array, and maps it into an arguments array (an array-like object) to be passed to the Array constructor function. The arguments array can't be sparse so the missing properties get set to undefined and become enumerable. Now we can use .map like intended
    – CervEd
    Oct 23, 2016 at 0:19
131

you can try:

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

Update (01/06/2018):

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.

Update (05/11/2019):

Another way, without using fill or from, that works for string of any length:

Array.apply(null, Array(3)).map(_ => 'abc') // ['abc', 'abc', 'abc']

Same as above answer. Adding for sake of completeness.

6
  • 2
    Nice. Shortest and simpler. Oct 27, 2014 at 21:59
  • 2
    +1 for simple handling. A shame that you cannot create an array of empty strings out of that. Apart from that very smart...
    – Quicker
    Oct 28, 2014 at 20:38
  • 1
    Array(6).join('a').split('a') gives me array of empty string.
    – Vivek
    Nov 4, 2014 at 6:53
  • 20
    This only works for 1 char strings, so it doesn't answer the question completely.
    – az_
    May 21, 2015 at 23:44
  • 3
    @AlfonsoVergara: In Javascript, String is a primitive (value-semantic) type; there's no way to get two strings to reference the same data (because strings aren't references in Javascript; they're values). You do have to watch out for reference semantics with objects and lists, but not with strings. Sep 11, 2016 at 7:37
112

...and Array.fill() comes to the rescue!

Used to write it all manually before knowing this one 🤦🏽‍♂️

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

Array(4).fill(0)  // =>  [0, 0, 0, 0]

You can also easily create a sequential array using fill() + map()


Array(4).fill('').map((_, i) => i + ' 🌵') // =>  ['0 🌵','1 🌵','2 🌵','3 🌵']


Array(3).fill(' 🌻').map((flower, i) => i + flower) // =>  ['0 🌻','1 🌻','2 🌻']


❗️Just be careful when creating objects and arrays using .fill() as they are referenced types❗️

That means Javascript will consider all the created items as being the same object (what may introduce unexpected bugs in case you want to further interact with the created objects)

// ❌ Careful when using .fill() with objects and arrays:

Array(3).fill({ value: 2 })  // =>  [{ value: 2 },{ value: 2 },{ value: 2 }]

The above line works, but it would be much safer to stick to the .fill().map() pattern. Like this:

// 👍🏽 Much better!

Array(3).fill().map(item => ({ value: 2 }))
2
  • Note that IE doesn't support it, but you can use a polyfill.
    – Yihao Gao
    Mar 12, 2021 at 4:30
  • 10
    There's a lot of things IE doesn't support I guess... :) Mar 30, 2021 at 19:08
72

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;
}
4
  • 19
    It's much more efficient to allocate all of the entries up front, with arr = new Array(len);, then assign to them by index in the loop, i.e. arr[i] = value;. That way you only pay O(n) rather than having to keep reallocating the array as it grows. In general, it's always better to avoid growing arrays by appending when possible. If you know the final size, use it.
    – Tom Karzes
    Aug 8, 2016 at 20:01
  • 73
    Array.from({length:5}).map(x => 2)
    – noobninja
    Jan 5, 2019 at 18:07
  • 4
    @noobninja: great solution; you should re-enter it as an answer so it can be upvoted.
    – jsalvata
    Sep 9, 2019 at 8:05
  • Here's an optimised version of the latter: function fillArray(value, len) { for (let n = [], u = 0; u < len; u++) n.push(value); return n }
    – undefined
    Jan 14, 2021 at 17:40
51

If you need to repeat an array, use the following.

Array(3).fill(['a','b','c']).flat() 

will return

Array(9) [ "a", "b", "c", "a", "b", "c", "a", "b", "c" ]
3
  • 1
    great oneliner using an existing array, what I needed.
    – gneric
    May 28, 2020 at 15:12
  • 2
    Array(3).fill(['a','b','c']).flat()
    – yongfa365
    Aug 1, 2020 at 5:16
  • great answ. tnx @etoxin Mar 25 at 9:32
47

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]

2
  • Nice, 👍 this is the best approach if you need the element to dynamic
    – IliasT
    Apr 22, 2019 at 20:44
  • Array.from({length:5}, i => 1) => i is is undefined since it represents empty value Array.from({length:5}, (e, i)=>i) => e is undefined since it represents empty value. It should be Array.from({length:5}, v => 1) and Array.from({length:5}, (v, i)=>i) Jun 5, 2019 at 16:22
40

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);
2
  • 3
    _.times(length, _.constant(value)) Nov 17, 2014 at 20:19
  • 1
    from the docs : _.fill(Array(3), 2); Which is not far from ES6
    – kert
    May 4, 2015 at 22:11
19

[c] * n can be written as:

Array(n+1).join(1).split('').map(function(){return c;})

so for [2] * 5

Array(6).join(1).split('').map(function(){return 2;})
2
  • Actually, wouldn't Array(6).join(2).split('') be easier? Why would you need the map?
    – Angela
    Feb 4, 2014 at 16:41
  • 5
    that returns ["2", "2", "2", "2", "2"], instead of [2, 2, 2, 2, 2].
    – brook hong
    Feb 11, 2014 at 6:54
14

You can also extend the functionality of Array like so:

Array.prototype.fill = function(val){
    for (var i = 0; i < this.length; i++){
        this[i] = val;
    }
    return this;
};
// used like:
var arry = new Array(5)​.fill(2);
// or
var arry = new Array(5);
arry.fill(2);


​console.log(arry);​ //[2, 2, 2, 2, 2] 

I should note that extending the functionality of built-in objects can cause problems if you are working with 3rd-party libraries. Always weigh this into your decisions.

8
  • Note that if you pass an object into fill each index in the array will refer to the same object, so changing one will change all of them. This isn't too hard to solve if it becomes an issue.
    – Shmiddty
    Sep 19, 2012 at 22:00
  • I don't get why many javascript users are unaware of the requirement not to prototype native functions.
    – brooNo
    Aug 13, 2015 at 13:46
  • 2
    A fill method has been added in ES6. So I wouldn't recommend adding your own stuff to the prototype, you're gonna overwrite the faster and more capable version. Aug 28, 2015 at 11:03
  • 1
    @JanusTroelsen To avoid overwrite javascript or 3rd-party libraries you can check if exists prior to declare it. if (!Array.prototype.fill) { }
    – Oliver
    Jun 16, 2016 at 15:56
  • 1
    @JanusTroelsen What do you mean by "real polyfill"?. I used a polifyll. I mean: check for feature detection and implementation in case it is not.
    – Oliver
    Jun 16, 2016 at 16:14
10

In the Node.js REPL:

> Array.from({length:5}).map(x => 2)
[ 2, 2, 2, 2, 2 ]
1
6

In case you need to repeat an array several times:

var arrayA = ['a','b','c'];
var repeats = 3;
var arrayB = Array.apply(null, {length: repeats * arrayA.length})
        .map(function(e,i){return arrayA[i % arrayA.length]});
// result: arrayB = ['a','b','c','a','b','c','a','b','c']

inspired by this answer

1
6

Use this function:

function repeatElement(element, count) {
    return Array(count).fill(element)
}
>>> repeatElement('#', 5).join('')
"#####"

Or for a more compact version:

const repeatElement = (element, count) =>
    Array(count).fill(element)
>>> repeatElement('#', 5).join('')
"#####"

Or for a curry-able version:

const repeatElement = element => count =>
    Array(count).fill(element)
>>> repeatElement('#')(5).join('')
"#####"

You can use this function with a list:

const repeatElement = (element, count) =>
    Array(count).fill(element)

>>> ['a', 'b', ...repeatElement('c', 5)]
['a', 'b', 'c', 'c', 'c', 'c', 'c']
5

No easier way. You need to make a loop and push elements into the array.

4
  • Thanks! Before I accept, is push better or concat better, in terms of efficiency? Sep 19, 2012 at 21:35
  • CONCAT needs to inspect two arrays, PUSH just adds another element, so I would expect PUSH to be more efficient in general, but for the IDENTICAL DATA I think Guffa's answer nails it. Sep 19, 2012 at 21:38
  • No need for loops, see my answer. Jun 4, 2013 at 13:12
  • @JanusTroelsen, no need to loop unless you want an efficient way to do this action. Yours is one of the slower impementation you can find. push() to [] is the fastest.
    – chrilith
    Mar 6, 2015 at 10:40
3

I discovered this today while trying to make a 2D array without using loops. In retrospect, joining a new array is neat; I tried mapping a new array, which doesn't work as map skips empty slots.

"#".repeat(5).split('').map(x => 0)

The "#" char can be any valid single character. The 5 would be a variable for the number of elements you want. The 7 would be the value you want to fill your array with.

The new fill method is better, and when I coded this I didn't know it existed, nor did I know repeat is es6; I'm going to write a blog post about using this trick in tandem with reduce to do cool things.

http://jburger.us.to/2016/07/14/functionally-create-a-2d-array/

3

Try This:

"avinash ".repeat(5).trim().split(" ");
3

You can use the SpreadOpeator and the map() function to create an array with the same element repeated multiple times.

function fillArray(value,len){
       return [...Array(len).keys()].map(x=> value);
   }
2

This function creates an array of (length) elements where each element equals (value) as long as (value) is an integer or string of an integer. Any decimal numbers will be truncated. If you do want decimal numbers, replace "parseInt(" with "parseFloat("

function fillArray(length, intValue) {
     var vals = (new Array(length + 1)).join(intValue + '|').split('|').slice(0,length);
     for(var i = 0; i < length; i += 1) {
         vals[i] = parseInt(vals[i]);
     }
     return vals;
}

Examples:

fillArray(5, 7) // returns [7,7,7,7,7]
fillArray(5, 7.5) // returns [7,7,7,7,7]
fillArray(5, 200) // returns [200,200,200,200,200]
2

I had problems with the mentioned methods when I use an array like

var array = ['foo', 'bar', 'foobar'];
var filled = array.fill(7);

//filled should be ['foo', 'bar', 'foobar', 'foo', 'bar', 'foobar', 'foo']

To get this I'm using:

Array.prototype.fill = function(val){
    var l = this.length;
    if(l < val){
        for(var i = val-1-l; i >= 0; i--){
            this[i+l] = this[i % l];
        }
    }
    return this;
};
1
  • This is nice, but should probably be named cycle.
    – Drenmi
    Apr 23, 2015 at 9:59
2

Another one-liner:

Array.prototype.map.call([]+Array(5+1),function(){ return '2'; })
2

Improving on Vivek's answer, this works for strings of any length, to populate an array of length n: Array(n+1).join('[string to be repeated][separator]').split('[separator]').slice(0, n)

2

var finalAry = [..."2".repeat(5).split("")].map(Number);
console.log(finalAry);

0

If you are using a utlity belt like lodash/underscore you can do it like this :)

let result = _.map(_.times(foo), function() {return bar})
0

Can be used as a one-liner too:

function repeat(arr, len) {
    while (arr.length < len) arr = arr.concat(arr.slice(0, len-arr.length));
    return arr;
}
0

This could be another answers.

let cards = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"];

let totalCards = [...cards, ...cards, ...cards, ...cards];

Not the answer you're looking for? Browse other questions tagged or ask your own question.