885

What is the most efficient way to create an arbitrary length zero filled array in JavaScript?

12
  • 7
    Some actual data on this: jsperf.com/zeroarrayjs Commented May 15, 2015 at 21:33
  • 9
    ES6 fill allows to do this natively. Commented Sep 26, 2015 at 22:25
  • 1
    arr = new Array(length+1).joint(character).split(''); Commented Nov 29, 2015 at 19:05
  • 5
    UPDATE 2016: Another custom benchmark here: jsfiddle.net/basickarl/md5z0Lqq Commented Jul 26, 2016 at 14:11
  • 4
    let i = 0; Array.from(Array(10), ()=>i++); Commented Oct 3, 2017 at 20:51

46 Answers 46

1
2
3

Anonymous function:

(function(n) { while(n-- && this.push(0)); return this; }).call([], 5); // => [0, 0, 0, 0, 0] 

A bit shorter with for-loop:

(function(n) { for(;n--;this.push(0)); return this; }).call([], 5); // => [0, 0, 0, 0, 0] 

Works with any Object, just change what's inside this.push().

You can even save the function:

function fill(size, content) { for(;size--;this.push(content)); return this; } 

Call it using:

var helloArray = fill.call([], 5, 'hello'); // => ['hello', 'hello', 'hello', 'hello', 'hello'] 

Adding elements to an already existing array:

var helloWorldArray = fill.call(helloArray, 5, 'world'); // => ['hello', 'hello', 'hello', 'hello', 'hello', 'world', 'world', 'world', 'world', 'world'] 

Performance: http://jsperf.com/zero-filled-array-creation/25

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

1 Comment

'0 '.repeat(200).split(' ')
3

In my testing by far this is the fastest in my pc

takes around 350ms for 100 million elements.

"0".repeat(100000000).split(''); 

for the same number of elements map(()=>0) takes around 7000 ms and thats a humungous difference

Comments

2

What everyone else seems to be missing is setting the length of the array beforehand so that the interpreter isn't constantly changing the size of the array.

My simple one-liner would be Array.prototype.slice.apply(new Uint8Array(length))

But if I were to create a function to do it fast without some hacky workaround, I would probably write a function like this:

var filledArray = function(value, l) { var i = 0, a = []; a.length = l; while(i<l) a[i++] = value; return a; } 

Comments

2

lodash:

_.fill(array, value) 

is a clean and cross-browser safe way to fill an array.

Comments

2
const item = 0 const arr = Array.from({length: 10}, () => item) 

const item = 0 const arr = Array.from({length: 42}, () => item) console.log('arr', arr)

Comments

2
let arr = [...Array(100).fill(0)] 

1 Comment

Your answer could be improved with additional supporting information. Please edit your answer to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
1

The fastest way to do that is with forEach =)

(we keep backward compatibility for IE < 9)

var fillArray = Array.prototype.forEach ? function(arr, n) { arr.forEach(function(_, index) { arr[index] = n; }); return arr; } : function(arr, n) { var len = arr.length; arr.length = 0; while(len--) arr.push(n); return arr; }; // test fillArray([1,2,3], 'X'); // => ['X', 'X', 'X'] 

2 Comments

That could be faster (I haven't checked), but it only works if the array already has values in it because forEach only loops over elements that have been set. So fillArray(new Array(100), 'X') won't do anything. The fallback code for IE works in either case.
It is not correct answer as the problem is that we DO NOT HAVE array yet. We have to make it and prepare it. Your answer uses already made array. I tested some algorithm with array of 100e6 items. Calculations was not easy but even that, preparing array from nothing takes the most time in that algorithm (80%).
1

I just use :

var arr = [10]; for (var i=0; i<=arr.length;arr[i] = i, i++); 

1 Comment

Code seems broken, didn't you mean something like for(var i=0, arr=[]; i<10; arr[i]=0, i++);?
1

Another nice option found here http://www.2ality.com/2013/11/initializing-arrays.html

function fillArrayWithNumbers(n) { var arr = Array.apply(null, Array(n)); return arr.map(function (x, i) { return i }); } 

1 Comment

This answer was already provided in the first answer.
1

Recursive solutions

As noted by several others, utilizing .concat() generally provides fast solutions. Here is a simple recursive solution:

function zeroFill(len, a){ return len <= (a || (a = [0])).length ? a.slice(0, len) : zeroFill(len, a.concat(a)) } console.log(zeroFill(5));

And a general-purpose recursive array fill function:

function fill(len, v){ return len <= (v = [].concat(v, v)).length ? v.slice(0, len) : fill(len, v) } console.log(fill(5, 'abc'));

Comments

1

new Array(2).fill(0)

will create

[ 0, 0 ]

More in the docs:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill

Comments

0

You can check if index exist or not exist, in order to append +1 to it.

this way you don't need a zeros filled array.

EXAMPLE:

var current_year = new Date().getFullYear(); var ages_array = new Array(); for (var i in data) { if(data[i]['BirthDate'] != null && data[i]['BirthDate'] != '0000-00-00'){ var birth = new Date(data[i]['BirthDate']); var birth_year = birth.getFullYear(); var age = current_year - birth_year; if(ages_array[age] == null){ ages_array[age] = 1; }else{ ages_array[age] += 1; } } } console.log(ages_array); 

1 Comment

Capitalization might be seen as "shouting", maybe you can edit it?
0

The fastest here is

(arr = []).length = len; arr.fill(0); 

1 Comment

why is this the fastest way?
-2
var str = "0000000...0000"; var arr = str.split(""); 

usage in expressions: arr[i]*1;

EDIT: if arr supposed to be used in integer expressions, then please don't mind the char value of '0'. You just use it as follows: a = a * arr[i] (assuming a has integer value).

17 Comments

My downvote sorry. This is terse but not efficient, as you will be creating a string first then performing a string operation, which tend to be slow, and you would still need to then convert the resultant strings to ints, which is also slow.
BTW, the question didn't state by what kind of "zeros" that array must be filled. Regarding performance - I think it should be faster than all previous solutions. Remenber .join("") for string concatenation?
Thevs - you're welcome to profile and prove me wrong. I think it's a stretch to interpret 'zero' as "the string '0'". Nobody else did. Also, just because join is fast for string concatenation does not mean split is the fastest way to create an array.
I just benchmarked this - it's ~33% slower in a range of crude tests and it has the more serious problem of requiring a literal string of the right length.
@dip: To be more clear: I gave an exact answer to your exact question. And in this exact case my solution is faster.
|
-2

I know this isn't the purpose of the question, but here's an out-of-the-box idea. Why? My CSci professor noted that there is nothing magical about 'cleansing' data with zero. So the most efficient way is to NOT do it at all! Only do it if the data needs to be zero as an initial condition (as for certain summations) -- which is usually NOT the case for most applications.

1 Comment

I thought of the same idea. Here's some bare-bones code that implements it using Proxy(): new Proxy(Array(length), { get(target, prop, receiver) { const value = Reflect.get(...arguments); return value !== undefined ? value : 0; } })
-6

return Array( quantity ).fill(1).map( n => return n * Math.abs(~~(Math.random() * (1000 - 1 + 1)) + 1) );

One line.

2 Comments

.fill() only works in newer browsers, so it creates runtime problems
SyntaxError: Unexpected token return. Other than that, the gist of your solution is Array(quantity).fill(1), which had been posted already. The rest is a distraction.
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.