Repeat an array with multiple elements multiple times in JavaScript
No need for any library, you can use Array.from
to create an array of arrays you want repeated, and then flatten using [].concat
and spread:
const makeRepeated = (arr, repeats) => [].concat(...Array.from({ length: repeats }, () => arr)); console.log(makeRepeated([1, 2, 3], 2));
On newer browsers, you can use Array.prototype.flat
instead of [].concat(...
:
const makeRepeated = (arr, repeats) => Array.from({ length: repeats }, () => arr).flat(); console.log(makeRepeated([1, 2, 3], 2));
You can use the Array
constructor along with its fill
method to fill it a number of times of the array you want to repeat, then concat
them (the subarrays) into a single array:
const repeatedArray = [].concat(...Array(num).fill(arr));
Note: On older browsers (pre-ES6), you can use Function#apply
to mimic the rest syntax above (concat
will be called with each of the sub arrays passed to it as argument):
var repeatedArray = [].concat.apply([], Array(num).fill(arr));
Example:
const repeat = (a, n) => Array(n).fill(a).flat(1)console.log( repeat([1, 2], 3) )
Recursive alternative:
const repeat = (a, n) => n ? a.concat(repeat(a, --n)) : [];console.log( repeat([1, 2], 3) )