How to 'repeat' an array n times

  • A+

In python you can do:

arr = [1,2,3] * 3 print(arr) 



Is there a concise way of doing this in java script? The best I can think of is something like:

let arr2 = [...arr, ...arr, ...arr] 

but if I wanted to do this 100 times it would be impractical. In python I would just multiply it by 100.


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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: