JavaScript: fill array with N items


I needed to fill an array with N items in JavaScript. However, this also needed to work in Internet Explorer 11.

Although there’s Array.from() and Array.fill(), I couldn’t use them without requiring a polyfill.

I ended up finding a Stackoverflow answer that uses Array.apply:

Array.apply(null, { length: 10 });
[ undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined ]

You can map and replace the value so it’s the index number instead of undefined so it’s the index number instead of undefined:

Array.apply(null, { length: 10 }).map(function(_, index) {
  return index;
});
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

If you’re transpiling ES6 down to ES5, you can use spread syntax with Object.keys():

[...Array(10).keys()];


Please support this site and join our Discord!