JS: Range Function for Array 📜
There's no builtin range function to create a array.
A Simple Range Function
/* a simple range function */ console.log(Array.from((Array(4)).keys())); /* [ 0, 1, 2, 3 ] */
xah_range
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. Any min, max, step can be negative. If min ≻ max, step must be negative. 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))); // s------------------------------ // test console.log(xah_range(0, 5)); // [ 0, 1, 2, 3, 4, 5 ] console.log(xah_range(3, 7)); // [ 3, 4, 5, 6, 7 ] console.log(xah_range(0, 10, 2)); // [ 0, 2, 4, 6, 8, 10 ] console.log(xah_range(0, 10, 3)); // [ 0, 3, 6, 9 ] console.log(xah_range(4, -4, -2)); // [ 4, 2, 0, -2, -4 ]