What is the most efficient way to create an arbitrary length zero filled array in JavaScript?
46 Answers
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
1 Comment
'0 '.repeat(200).split(' ')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
let arr = [...Array(100).fill(0)] 1 Comment
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
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.I just use :
var arr = [10]; for (var i=0; i<=arr.length;arr[i] = i, i++); 1 Comment
for(var i=0, arr=[]; i<10; arr[i]=0, i++);?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
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
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
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
The fastest here is
(arr = []).length = len; arr.fill(0); 1 Comment
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
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.
return Array( quantity ).fill(1).map( n => return n * Math.abs(~~(Math.random() * (1000 - 1 + 1)) + 1) );
One line.
2 Comments
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.
let i = 0; Array.from(Array(10), ()=>i++);