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; };
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.
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 .
In ES6 using Array fill() method
console.log( Array(5).fill(2) ) //=> [2, 2, 2, 2, 2]
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