JavaScript: How to add x to an array x times?

I suppose this seems like filling an array, but I wonder if it can be simplified at all.

var arr = [1,2,3], x = 5; for (var i=0; i<x; i++) { arr.push(x); } console.log(arr); //=> [1, 2, 3, 5, 5, 5, 5, 5] 

Is there a way to do this without using a for loop?


Update

Despite the fact that there are smart solutions, for-loop seems to be the most effective

array-fill-2 Jsperf tests

+6
source share
3 answers

If you are not punished for every line of code you write, this code is fine: concise and very clear.

If you get punished, just use:

 for (var i = 0; i < x; i++) arr.push(x); 

in one line :-)

In addition, the function in the following areas will be the best choice:

 arr = appendXCopiesOfX (arr, x); 

but I don’t think that you are really typing something there, because, as already mentioned, there should be very few problems understanding such a short cycle.

All in all, it is probably a waste of time and effort trying to improve what you have.

+3
source

Without for a loop :

 var arr = [1,2,3], x = 5; arr = arr.concat(Array.apply(null, Array(x)).map(function() { return x; })); // or even arr = arr.concat(Array.apply(null, Array(x)).map(x.valueOf, x)); 
+4
source

For those using ES6, and have encountered this problem. Try using Array.fill () https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/fill

I used this method when testing to generate mock data for x rows without the need for a loop.

Edit: Sorry, I was on that. This code will generate an x ​​long array, but they will all have the same value. A better code snippet is at the end of this post.

 newOrdersX: function(x) { return Array(x).fill({ name: faker.random.name() }); }` 

This level will consist of an array of x, but each value will be different. Note that .fill() still needs to be called or it will not work.

 newOrdersX: function(x) { return Array(x).fill().map(() => ({ name: faker.random.name() })); }` 
+1
source

All Articles