Create an array with same element repeated multiple times

JavascriptArraysRepeat

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

In ES6 using Array fill() method

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

Solution 2 - Javascript

>>> 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 3 - Javascript

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.

Solution 4 - Javascript

...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 }))

Solution 5 - Javascript

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 6 - Javascript

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 7 - Javascript

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

Solution 8 - Javascript

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" ]

Solution 9 - Javascript

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

Solution 10 - Javascript

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.

Solution 11 - Javascript

In the Node.js REPL:

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

Solution 12 - Javascript

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

Solution 13 - Javascript

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']

Solution 14 - Javascript

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

Solution 15 - Javascript

Try This:

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

Solution 16 - Javascript

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

Solution 17 - Javascript

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]

Solution 18 - Javascript

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

Solution 19 - Javascript

Another one-liner:

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

Solution 20 - Javascript

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/

Solution 21 - Javascript

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)

Solution 22 - Javascript

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

Solution 23 - Javascript

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

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

Solution 24 - Javascript

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

Solution 25 - Javascript

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

Solution 26 - Javascript

I needed a way to repeat/loop an array (with n items) m times.

For example, distributing a list (of persons) to a week/month. Let's say I have 3 names, and I want to them to repeat in a week:

fillArray(["Adam", "Blair", "Curtis"], 7); // returns ["Adam", "Blair", "Curtis", "Adam", "Blair", "Curtis", "Adam"]

function fillArray(pattern, count) {
    let result = [];
    if (["number", "string"].includes(typeof pattern)) {
        result = new Array(5);
        result.fill(pattern);
    }
    else if (pattern instanceof Array) {
        for (let i = 0; i < count; i++) {
            result = result.concat(pattern);
        }
        result = result.slice(0, count);
    }
    return result;
}

fillArray("a", 5);        // ["a", "a", "a", "a", "a"]
fillArray(1, 5);          // [1, 1, 1, 1, 1]
fillArray(["a", "b"], 5); // ["a", "b", "a", "b", "a"]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCurious2learnView Question on Stackoverflow
Solution 1 - JavascriptNiko RuotsalainenView Answer on Stackoverflow
Solution 2 - JavascriptJanus TroelsenView Answer on Stackoverflow
Solution 3 - JavascriptVivekView Answer on Stackoverflow
Solution 4 - JavascriptFelipe ChernicharoView Answer on Stackoverflow
Solution 5 - JavascriptGuffaView Answer on Stackoverflow
Solution 6 - JavascriptThomsonView Answer on Stackoverflow
Solution 7 - JavascriptyurisichView Answer on Stackoverflow
Solution 8 - JavascriptetoxinView Answer on Stackoverflow
Solution 9 - Javascriptbrook hongView Answer on Stackoverflow
Solution 10 - JavascriptShmiddtyView Answer on Stackoverflow
Solution 11 - JavascriptnoobninjaView Answer on Stackoverflow
Solution 12 - JavascriptHenrik ChristensenView Answer on Stackoverflow
Solution 13 - JavascriptKen MuellerView Answer on Stackoverflow
Solution 14 - JavascriptDiodeus - James MacFarlaneView Answer on Stackoverflow
Solution 15 - JavascriptAvinashView Answer on Stackoverflow
Solution 16 - JavascriptAnishJoshiView Answer on Stackoverflow
Solution 17 - JavascriptTxRegexView Answer on Stackoverflow
Solution 18 - JavascriptXaverView Answer on Stackoverflow
Solution 19 - JavascriptFilip HermansView Answer on Stackoverflow
Solution 20 - JavascriptMagical GordonView Answer on Stackoverflow
Solution 21 - JavascriptTigregalisView Answer on Stackoverflow
Solution 22 - JavascriptAmaldev psView Answer on Stackoverflow
Solution 23 - JavascriptShane RogersView Answer on Stackoverflow
Solution 24 - JavascriptSarsaparillaView Answer on Stackoverflow
Solution 25 - JavascriptZenitView Answer on Stackoverflow
Solution 26 - JavascriptakinuriView Answer on Stackoverflow