How to 'repeat' an array n times
You could do this:
var repeated = [].concat(... new Array(100).fill([1, 2, 3]));
That creates an array of a given length (100 here) and fills it with the array to be repeated ([1, 2, 3]
). That array is then spread as the argument list to [].concat()
.
Oh wait just
var repeated = new Array(100).fill([1, 2, 3]).flat();
would be a little shorter.
One quick way is joining the array, repeating it using string.repeat(), then splitting it and finally using ES6 Spreads
The other answer are probably better. This is just a simpel one-liner.
let arr = [1, 2, 3];
let res = [...arr.join("").repeat(3).split("").map(Number)];
console.log(res);
Use Array.from()
to create an array with a length of the multiplier, where each item contains the original array. Then use Array.flat()
to convert to a single array:
const multiplyArray = (arr, length) =>
Array.from({ length }, () => arr).flat()
const arr = [1,2,3]
const arr2 = multiplyArray(arr, 3)
console.log(arr2)
You could create an array with the wanted length and map the values.
var array = [1, 2, 3],
result = Array.from({ length: 3 * array.length }, (_, i) => array[i % array.length]);
console.log(result);