JS: Range Function for Array 🚀

By Xah Lee. Date: . Last updated: .

There's no builtin range function to create a array.

This is the best function for generating an array. Most efficient and fastest, functional style, and without hack.

/*
xah_range(min, max) → return a array from min to max, inclusive.
xah_range(min, max, step) → in increment of step.
If step is not integer, then max may not be included.
http://xahlee.info/js/js_range_array.html
version 2019-10-31
*/

const xah_range = ((
  min,
  max,
  step = 1,
) => (Array(Math.floor((max - min) / step) + 1).fill(min).map(
  (x, i) => (x + i * step),
)));

back to Array How-To

JavaScript, Array