1

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]
0

4 Answers 4

4

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:

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

4 Comments

Ah, so you're looking for a magic function that doesn't (even internally) have to iterate over the loop? I...don't think that exists.
getting Uncaught TypeError: undefined is not a function jsfiddle.net/L6hj442e
@Alex: which is why I clarified that it was "in compliant browsers", albeit I'd only had a chance to test in Chrome at that point (before work took me afk for a little while).
Thanks for the answer, since i cant use this because of browser compatibility
2
Array.apply(null, new Array(5)).map(Number.prototype.valueOf, 0))

Useful article Initializing arrays

1 Comment

if this answer solved your problem, you should approve it, maybe editing the question to setup the answer better.
1

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]

1 Comment

Thanks for the answer....actually we are following clean code strategy ....so i cant use this stuffs
1

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.

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.