Categories
arrays javascript repeat

Repeat an array with multiple elements multiple times in JavaScript

In JavaScript, how can I repeat an array which contains multiple elements, in a concise manner?

In Ruby, you could do

irb(main):001:0> ["a", "b", "c"] * 3
=> ["a", "b", "c", "a", "b", "c", "a", "b", "c"]

I looked up the lodash library, and didn’t find anything that was directly applicable. Feature request: repeat arrays. is a feature request for adding it to lodash, and the best workaround given there is

const arrayToRepeat = [1, 2, 3];
const numberOfRepeats = 3;
const repeatedArray = _.flatten(_.times(numberOfRepeats, _.constant(arrayToRepeat)));

The questions Most efficient way to create a zero filled JavaScript array? and Create an array with same element repeated multiple times focus on repeating just a single element multiple times, whereas I want to repeat an array which has multiple elements.

Using reasonably well-maintained libraries is acceptable.