Is there a more compact way to do this sort of initialization?
for (var i = 0; i < arraySize; i++) array[i] = value;
Is there a more compact way to do this sort of initialization?
for (var i = 0; i < arraySize; i++) array[i] = value;
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.
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;
while is 2 times slower than for in JavaScript, and simple checks like if (number) are also slower than if (number === 0) because of type conversion (this also applies to booleans, strings and nulls). My jsPerf tests taught me this.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);
for is 2 times faster than while.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
null, but empty. This is a big difference. For example [null].map(x=>1) gives [1], but [,].map(x=>1) stays [,]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);})
var arr = (new Array(5)).map(() => 1); doesn't work?new Array(5) when we do a map aren't we operating on an array? Also, this [1,undefined,3].map(() => 5) works as expected. It doesn't skip undefinedFor 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.
for (var i = 0; i < arraySize; ++i) has almost the same performance as your code, but looks cleaner. But while (arraySize--) is 2 times slower.array is more effective than starting array[0].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)
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}
[...Array(30)].map((_, i) => i);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++).
Array(arraySize).fill(value) is very slow for huge arrays (~14s for arraySize=1e8 on my machine) produces a [holey array] and (https://v8.dev/blog/elements-kinds) in v8, with worse performance characteristics than a "packed array", and is therefore suboptimal.
The push method
let array = []
for(let i = 0; i < arraySize; i++){
array.push(value)
}
is worse for smaller arrays (arraySize <= 1e7) than the fill method, but less bad for 1e8.
All the other suggestions in the answers seem to be silly hacks with even worse performance.
Therefore, the only right answer is to use a TypedArray whenever possible:
let array = new Int32Array(arraySize) // this array is already 0-initialized
array.fill(value) // only necessary if value != 0
For arraySize = 1e7 with value = 1 this only takes 4ms on my machine, as opposed to 15ms for the fill method and 70ms for the push method.
let arraySize = 1e7
let value = 1
let t0 = performance.now()
let fillArray = new Array(arraySize).fill(value)
let t1 = performance.now()
let pushArray = []
for(let i = 0; i < arraySize; i++){
pushArray.push(value)
}
let t2 = performance.now()
let array = new Int32Array(arraySize)
array.fill(value)
let t3 = performance.now()
console.log(t1 - t0, t2 - t1, t3 - t2)
(Feel free to benchmark more properly, but the result seems so consistent that it's unnecessary.)
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