Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push multiple zeros to an already existing array

I found on this link how to create arrays with a chosen number of zeros. Most efficient way to create a zero filled JavaScript array?

But my question is, imagine i already have a array

var a = ['hihi','haha']

how can i add 12 zeros after my two first elements ? So that it becomes :

a = ['hihi','haha',0,0,0,0,0,0,0,0,0,0,0,0];

of course I could go for a

for(var i = 0; i < 12, i++){
  a.push(0);
}

but is there a one line method ? something like

a.push(6*[0]);
like image 889
Bidoubiwa Avatar asked Dec 25 '22 06:12

Bidoubiwa


1 Answers

You can use Array.prototype.concat() and Array.prototype.fill()

  1. Create an array with size 12 and fill 0 by using Array.prototype.fill()
  2. Then concatenate with existing array using Array.prototype.concat()

var a = ['hihi', 'haha'].concat(Array(12).fill(0));


document.write('<pre>' + JSON.stringify(a, null, 3) + '</pre>');
like image 56
Pranav C Balan Avatar answered Jan 04 '23 23:01

Pranav C Balan