Initializing an Array with a Single Value
JavascriptJavascript Problem Overview
Is there a more compact way to do this sort of initialization?
for (var i = 0; i < arraySize; i++) array[i] = value;
Javascript Solutions
Solution 1 - Javascript
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.
Solution 2 - Javascript
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;
Solution 3 - Javascript
The OP seems to be after compactness in a single-use scenario over efficiency and re-usability. For others looking for efficiency, here's an optimization that hasn't been mentioned yet. Since you know the length of the array in advance, go ahead and set it before assigning the values. Otherwise, the array's going to be repeatedly resized on the fly -- not ideal!
function initArray(length, value) {
var arr = [], i = 0;
arr.length = length;
while (i < length) { arr[i++] = value; }
return arr;
}
var data = initArray(1000000, false);
Solution 4 - Javascript
This is not as compact but is arguably more direct.
array = Array.apply(null, new Array(arraySize)).map(function () {return value;});
Solution 5 - Javascript
This is an old question, but I use this in modern JS:
[...new Array(1000000)].map(()=>42);
Solution 6 - Javascript
This is not likely to be better than any of the techniques above but it's fun...
var a = new Array(10).join('0').split('').map(function(e) {return parseInt(e, 10);})
Solution 7 - Javascript
For efficiency, I would avoid push
. So simply
for (var i = 0; i < arraySize; i++) array[i] = value;
For IE10:
array = new Array(arraySize);
for (var i = 0; i < arraySize; i++) array[i] = value;
Edit: modified as discussed in the comments.
Solution 8 - Javascript
You can use Js Array constructor:
const arr = new Array(3)
This will create an array of size 3 and all elements are null ([null, null, null]
)
So to create an array and initialize it with some value simply do:
const arr = new Array(3).fill(value)
Regards
Solution 9 - Javascript
If you need to do it many times, you can always write a function:
function makeArray(howMany, value){
var output = [];
while(howMany--){
output.push(value);
}
return output;
}
var data = makeArray(40, "Foo");
And, just for completeness (fiddling with the prototype of built-in objects is often not a good idea):
Array.prototype.fill = function(howMany, value){
while(howMany--){
this.push(value);
}
}
So you can now:
var data = [];
data.fill(40, "Foo");
Update: I've just seen your note about arraySize
being a constant or literal. If so, just replace all while(howMany--)
with good old for(var i=0; i<howMany; i++)
.
Solution 10 - Javascript
Stumbled across this one while exploring array methods on a plane.. ohhh the places we go when we are bored. :)
var initializedArray = new Array(30).join(null).split(null).map(function(item, index){
return index;
});
.map()
and null
for the win! I like null because passing in a string like up top with '0' or any other value is confusing. I think this is more explicit that we are doing something different.
Note that .map()
skips non-initialized values. This is why new Array(30).map(function(item, index){return index});
does not work. The new .fill()
method is preferred if available, however browser support should be noted as of 8/23/2015.
Desktop (Basic support)
- Chrome 45 (36 1)
- Firefox (Gecko) 31 (31)
- Internet Explorer Not supported
- Opera Not supported
- Safari 7.1
From MDN:
[1, 2, 3].fill(4); // [4, 4, 4]
[1, 2, 3].fill(4, 1); // [1, 4, 4]
[1, 2, 3].fill(4, 1, 2); // [1, 4, 3]
[1, 2, 3].fill(4, 1, 1); // [1, 2, 3]
[1, 2, 3].fill(4, -3, -2); // [4, 2, 3]
[1, 2, 3].fill(4, NaN, NaN); // [1, 2, 3]
Array(3).fill(4); // [4, 4, 4]
[].fill.call({ length: 3 }, 4); // {0: 4, 1: 4, 2: 4, length: 3}
Solution 11 - Javascript
In my testing by far this is the fastest in my pc. But note this method may not not be suitable for all use cases.
takes around 350ms for 100 million elements.
"0".repeat(100000000).split('');
for the same number of elements [...new Array(100000000)].map(()=>0)
takes around 7000 ms and thats a humungous difference