124

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

for (var i = 0; i < arraySize; i++) array[i] = value;
2
  • Possible duplicate of Most efficient way to create a zero filled JavaScript array? Commented Jun 1, 2016 at 6:46
  • The canonical answer is "no", although "fill()" is this wrapped in a function. There are lots of kewl ways to do it, all of which are less readable and less efficient. Commented Jun 6 at 17:25

13 Answers 13

221

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.

Sign up to request clarification or add additional context in comments.

5 Comments

@Perry. You know, when the browser with 6% of the market does not support the standard it is the problem of that browser
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.
Plus, I think now, IE support should not be much of an issue.
It took me an hour to realise that fill makes no sense when you work with nested arrays. When populating [0, 0] it just fills in all 0 index values for the nested array. Dangerous, to be used with care.
48
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;

8 Comments

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.
true: "for(var i = arraySize; i--;) array.push(value);" then :-) but i think you figured that out already
You’re right — that syntax does shave five characters off. ;-)
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.
new Array(len).fill(0);
|
18

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

[...new Array(1000000)].map(() => 42);

Comments

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);

2 Comments

In JavaScript, for is 2 times faster than while.
I wouldn't say it's as exact as that: 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.
9

This is not as compact but is arguably more direct.

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

Comments

8

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

1 Comment

The elements aren't null, but empty. This is a big difference. For example [null].map(x=>1) gives [1], but [,].map(x=>1) stays [,]
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);})

4 Comments

Can you explain why var arr = (new Array(5)).map(() => 1); doesn't work?
The map() method only works on values in the array. It skips undefined elements.
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
From the mozilla documentation at developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…: 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).
4

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.

4 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.
Yes, but memory allocation for array is more effective than starting array[0].
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.
From [Build/12] (channel9.msdn.com/Events/Build/2012/4-000) talk, IE10 need pre-allocation to be efficient. Ref [on Slide 54] (channel9.msdn.com/Events/Build/2012/4-000)
2

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}

1 Comment

This can nowadays (June 2019) easily be written as: [...Array(30)].map((_, i) => i);
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++).

Comments

1

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.