How to 'repeat' an array n times

  • A+
Category:Languages

In python you can do:

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

output:

[1,2,3,1,2,3,1,2,3] 

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.

Comment

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