Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing an Array with a Single Value

Tags:

javascript

Is there a more compact way to do this sort of initialization?

for (var i = 0; i < arraySize; i++) array[i] = value; 
like image 210
oldestlivingboy Avatar asked Oct 29 '10 07:10

oldestlivingboy


People also ask

Can you initialize an array with a variable?

You initialize an array variable by including an array literal in a New clause and specifying the initial values of the array. You can either specify the type or allow it to be inferred from the values in the array literal.

How do you initialize an entire array to 1 in Java?

If it's a primitive type, you can use Arrays. fill() : Arrays. fill(array, -1);

How do you initialize an array?

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.


2 Answers

One short way of doing it would be:

var arr = Array(arraySize).fill(value); 

Would make arr = Array [ 0, 0, 0, 0, 0 ] if arraySize == 5 and value == 0, for example.

like image 176
Klaus Byskov Pedersen Avatar answered Oct 14 '22 16:10

Klaus Byskov Pedersen


while(arraySize--) array.push(value); 

no initialization (that i know of)


Update

Since ever posting this answer 4 years ago, people seem to keep coming back here for this answer. For benchmarking purposes I made a JSPerf with some different solutions.

The solution above here isn't the quickest, although it's short. To stick to the same short style, but with a better performance:

while(size--) array[size] = value; 

Update Feb 2016 Updated the JSPerf with a new revision with more testcases.

If performance doesn't matter and you want a one-liner:

var value = 1234, // can be replaced by a fixed value     size  = 1000, // can be replaced by a fixed value     array = Array.apply(null,{length: size}).map(function() { return value; }); 

A more performant solution (in one, dirty, line): Be aware: this replaces existsing value, size and i variables in the scope

for(var i = 0, value = 1234, size = 1000, array = new Array(1000); i < size; i++) array[i] = value; 
like image 42
DoXicK Avatar answered Oct 14 '22 17:10

DoXicK