Alex Man
Alex Man

Reputation: 4886

initialize all the values in a javascript array to 0 without iteration

is there any way to make javascript array to initialize all the values to 0 without iteration like as shown below

var array = [1, 2, 3, 4, 5];

to

[0, 0, 0, 0, 0]

Upvotes: 1

Views: 280

Answers (4)

dandavis
dandavis

Reputation: 16726

i guess you don't need eval if you use JSON.parse() to build the empties and splice() to mutate the existing array instead of just making a new array full of zeros:

var r=[1, 2, 3, 4, 5];

[].splice.apply(r, 
   [0, r.length].concat( 
     JSON.parse("[0"+new Array(r.length).join(",0")+"]")  
));
alert(r); // shows: "0,0,0,0,0"

Answers based on map()/fill() will not affect the orig array as desired, but those solutions could use splice like the above answer to do so, the only difference then is how one build the zero-filled array.

EDIT: kudos to Gilsha, i was working on an eval-based answer when you reminded me that JSON would be enough.

Upvotes: 1

Gilsha
Gilsha

Reputation: 14591

Its a bit tricky. But it works

var array = [1, 2, 3, 4, 5];
array  = JSON.parse(JSON.stringify(array).replace(/(\d+)/g,0)); // Returns [0,0,0,0,0]

Upvotes: 1

Oleksandr T.
Oleksandr T.

Reputation: 77482

Array.apply(null, new Array(5)).map(Number.prototype.valueOf, 0))

Useful article Initializing arrays

Upvotes: 2

David Thomas
David Thomas

Reputation: 253308

You could, in compliant browsers, use Array.prototype.fill():

 var array = [1, 2, 3, 4, 5];
 array.fill(0); // [0, 0, 0, 0, 0]

References:

Upvotes: 4

Related Questions