Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I imagine this is similar to array padding, 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 any way to do this without using the for loop?


Update

Even though there's mover clever solutions, the for-loop seems to be the most performant

array-fill-2Benchmarks on jsperf

like image 994
Mulan Avatar asked Mar 19 '14 01:03

Mulan


People also ask

How do you add the same element multiple times in an array?

We can use the for loop to run the push method to add an item to an array multiple times. We create the fillArray function that has the value and len parameters. value is the value we want to fill in the array. len is the length of the returned array.

How do you repeat a value in JavaScript?

The repeat() method returns a string with a number of copies of a string. The repeat() method returns a new string. The repeat() method does not change the original string.


2 Answers

Unless you get penalised for each line of code you write, that code is fine: succinct and very understandable.

If you do get penalised, just use:

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

on a single line :-)

Beyond that, your best bet would be a function along the lines of:

arr = appendXCopiesOfX (arr, x);

but I don't think you're really gaining anything there since, as mentioned, there should be very little problem understanding such a small loop.

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

like image 59
paxdiablo Avatar answered Sep 24 '22 03:09

paxdiablo


Without for 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));
like image 36
xdazz Avatar answered Sep 20 '22 03:09

xdazz