117

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

for (var i = 0; i < arraySize; i++) array[i] = value;
oldestlivingboy
  • 2,914
  • 2
  • 21
  • 15
  • Possible duplicate of [Most efficient way to create a zero filled JavaScript array?](http://stackoverflow.com/questions/1295584/most-efficient-way-to-create-a-zero-filled-javascript-array) – Ninja Jun 01 '16 at 06:46

12 Answers12

209

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.

Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
  • 3
    Not supported on IE: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill#Browser_compatibility – Perry Feb 18 '16 at 09:39
  • 36
    @Perry. You know, when the browser with 6% of the market does not support the standard it is the problem of that browser – Slava Mar 03 '16 at 16:10
  • 26
    Be carefull with the fill function if the value is an object, because you may have the same object into the entire array, which may cause unwanted results. – Gregzenegair Dec 20 '16 at 21:14
  • Plus, I think now, IE support should not be much of an issue. – Anshuman Kumar Feb 21 '22 at 15:51
47
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;
DoXicK
  • 4,784
  • 24
  • 22
  • In many cases, “arraySize” wouldn’t be mutable (could be a constant or literal or — I know, bad practice — “array.length”). By representing the size as a variable, I made this bit unclear. – oldestlivingboy Oct 29 '10 at 08:02
  • 1
    true: "for(var i = arraySize; i--;) array.push(value);" then :-) but i think you figured that out already – DoXicK Oct 29 '10 at 13:42
  • 1
    You’re right — that syntax does shave five characters off. ;-) – oldestlivingboy Oct 29 '10 at 23:37
  • 3
    `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. – Triang3l Oct 25 '12 at 15:29
  • `array.push()` is known to be slower than `array[i]`. – Kyaw Tun Oct 25 '12 at 23:30
  • 3
    new Array(len).fill(0); – Muhammad Umer Oct 11 '14 at 21:25
  • @MuhammadUmer Array.prototype.fill() is a new technology, part of the ECMAScript 2015 (ES6) standard. from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill Good luck with using that. – Bruno Bronosky Jun 22 '15 at 19:55
16

This is an old question, but I use this in modern JS:

[...new Array(1000000)].map(() => 42);
maxshuty
  • 9,708
  • 13
  • 64
  • 77
Rick Love
  • 12,519
  • 4
  • 28
  • 27
10

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);
Aequitas
  • 570
  • 5
  • 6
  • 1
    In JavaScript, `for` is 2 times faster than `while`. – Triang3l Oct 25 '12 at 15:30
  • 2
    I wouldn't say it's as exact as that: http://www.stoimen.com/blog/2012/01/24/javascript-performance-for-vs-while/ Certainly you wouldn't want to always use either exclusively - that defeats their purpose. It should be the interpreter's/compiler's job to speed it up where it can, not yours. But even that isn't always true. – Aram Kocharyan Jan 27 '13 at 10:26
9

This is not as compact but is arguably more direct.

array = Array.apply(null, new Array(arraySize)).map(function () {return value;});
6

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);})
  • Can you explain why `var arr = (new Array(5)).map(() => 1);` doesn't work? – Bharat Gupta May 14 '18 at 02:54
  • 1
    The map() method only works on values in the array. It skips undefined elements. – Christopher Weiss May 15 '18 at 12:09
  • So after `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 `undefined` – Bharat Gupta May 16 '18 at 01:56
  • 2
    From the mozilla documentation at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map: map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value). – Christopher Weiss May 17 '18 at 13:16
  • Awesome. Thanks @Christopher! – Bharat Gupta May 17 '18 at 17:49
4

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

elkolotfi
  • 5,645
  • 2
  • 15
  • 19
3

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.

Kyaw Tun
  • 12,447
  • 10
  • 56
  • 83
  • `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. – Triang3l Oct 25 '12 at 15:26
  • Yes, but memory allocation for `array` is more effective than starting `array[0]`. – Kyaw Tun Oct 25 '12 at 23:10
  • 2
    No. If you start initializing an array from the end, hash tables will be used internally, but if you start initializing an array from 0, and you have only sequential indices, a true array will be used (at least in V8). JavaScript doesn't allocate (highest_index+1) elements, it allocates only initialized elements. – Triang3l Oct 29 '12 at 08:15
  • From [Build/12] (http://channel9.msdn.com/Events/Build/2012/4-000) talk, IE10 need pre-allocation to be efficient. Ref [on Slide 54] (http://channel9.msdn.com/Events/Build/2012/4-000) – Kyaw Tun Nov 02 '12 at 14:43
1

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}
Joshua Robinson
  • 3,430
  • 1
  • 27
  • 35
1

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++).

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
0

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

Ali
  • 166
  • 1
  • 8
0

Init an array with ascending numbers:

const myArray = [...new Array(1000)].map((e, i) => i);
console.log(myArray);

In case someone is looking to that here . . .

ranbuch
  • 1,584
  • 16
  • 14