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.
If n is a vector, then it must be the same length as v. Each element of n specifies the number of times to repeat the corresponding element of v. This syntax is not supported for table input. B = repelem (A,r1,...,rN) returns an array with each element of A repeated according to r1,...,rN.
Number of times to repeat each element, specified as a scalar or a vector. If n is a scalar, then all elements of v are repeated n times. If n is a vector, then each element of n specifies the number of times to repeat the corresponding element of v . In either case, n must be integer-valued.
The repeat () is an inbuilt function in julia which is used to construct an array by repeating the specified array elements with the specified number of times. repeat (A::AbstractArray, counts::Integer…) A::AbstractArray: Specified array. counts::Integer: Specified number of times each element get repeated.
We need to repeat some portion of the code for all the tasks mentioned above again and again. This tutorial will look into different methods to repeat the specific task N times in Python. The most common way to repeat a specific task or operation N times is by using the for loop in programming.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With