Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 'repeat' an array n times [duplicate]

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.

like image 204
Oamar Kanji Avatar asked Feb 28 '19 22:02

Oamar Kanji


People also ask

How to get the number of times a vector is repeated?

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.

How do you find the number of times an element is repeated?

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.

How to use repeat () function in Julia?

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.

How to repeat a specific task n times in Python?

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.


2 Answers

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.

like image 198
Pointy Avatar answered Sep 28 '22 10:09

Pointy


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);
like image 31
Nina Scholz Avatar answered Sep 28 '22 08:09

Nina Scholz