Create an array with same element repeated multiple times

Curious2learn picture Curious2learn · Sep 19, 2012 · Viewed 258.4k times · Source

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

Answer

Niko Ruotsalainen picture Niko Ruotsalainen · Dec 5, 2015

In ES6 using Array fill() method

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