0

If I want to create an array containing a piece of data for every minute of the year (525,600 elements for 365 day year) or (524,160 elements for 364 day year) is there a way to create an array with a set amount of elements inside all set to a value of 0?

const minutesOfTheYear = [];
minutesOfTheYear[0] = 0;
minutesOfTheYear[1] = 0;
minutesOfTheYear[2] = 0;
/* ... */
minutesOfTheYear[525,599] = 0;

I think I could use a for loop, setting the amount of loops to 525,600 and the index of the array amended to add by 1 each time, but what is the proper way to declare the new values within a for loop? Would this work?

for (let i = 0; i< 525599; i++) {
 minutesOfTheYear[i] = 0;
}

Or is there a line of code that just declares the size of the array and auto populates?

  • 1
    https://stackoverflow.com/questions/1295584/most-efficient-way-to-create-a-zero-filled-javascript-array/53029824 – gaitat Oct 19 '21 at 21:29

2 Answers2

0

Use Array.from():

const result = Array.from({ length: 524160 }, () => 0);

console.log(result);

The second argument is a map function - it is run once for each item in the array, and it must return the value for that item. In this example, it's simply returning 0.

Ro Milton
  • 2,281
  • 14
  • 9
0
Array(100).fill(0)  // length is 100
Ahmed I. Elsayed
  • 2,013
  • 2
  • 17
  • 30