Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array with same element repeated multiple times

In Python, where [2] is a list, the following code gives this output:

[2] * 5 # Outputs: [2,2,2,2,2] 

Does there exist an easy way to do this with an array in JavaScript?

I wrote the following function to do it, but is there something shorter or better?

var repeatelem = function(elem, n){     // returns an array with element elem repeated n times.     var arr = [];      for (var i = 0; i <= n; i++) {         arr = arr.concat(elem);     };      return arr; }; 
like image 558
Curious2learn Avatar asked Sep 19 '12 21:09

Curious2learn


People also ask

How do you repeat an array and time?

In Python, if you want to repeat the elements multiple times in the NumPy array then you can use the numpy. repeat() function. In Python, this method is available in the NumPy module and this function is used to return the numpy array of the repeated items along with axis such as 0 and 1.

How many times number repeated in array JS?

To check how many times an element appears in an array: Declare a count variable and set its value to 0 . Use the forEach() method to iterate over the array. Check if the current element is equal to the specific value. If the condition is met, increment the count by 1 .


1 Answers

In ES6 using Array fill() method

console.log(   Array(5).fill(2) ) //=> [2, 2, 2, 2, 2]
like image 66
Niko Ruotsalainen Avatar answered Oct 02 '22 02:10

Niko Ruotsalainen