JS: Range Function for Array

By Xah Lee. Date: . Last updated: .

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

0 Index Based Range Function

The easiest way to create a array from 0 to n is:

[... Array(n).keys()]

const range0 = ((n) => [...Array(n).keys()] ) ;

console.log ( range0(4) ); // [ 0, 1, 2, 3 ]

[see JS: Spread Operator]

[see JS: Array.prototype.keys]

General Range Function

Here's a general range function.

/* [
xah_range(min, max) → return a array from min to max, inclusive.
xah_range(min, max, step) → in steps of step.
if step is not integer, then max may not be included
http://xahlee.info/js/javascript_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 )) )));

// test
console.log( xah_range(3, 7) );
console.log( xah_range(3, 4.5) );
console.log( xah_range(3.2, 4.5) );
console.log( xah_range(3, 5, .25) );
console.log( xah_range(5, 3, -.25) );
console.log( xah_range(3, 5, .7) );

// [ 3, 4, 5, 6, 7 ]
// [ 3, 4 ]
// [ 3.2, 4.2 ]
// [
//      3, 3.25,  3.5,
//   3.75,    4, 4.25,
//    4.5, 4.75,    5
// ]
// [
//      5, 4.75,  4.5,
//   4.25,    4, 3.75,
//    3.5, 3.25,    3
// ]
// [ 3, 3.7, 4.4 ]

Here's pre-ES2015 version:

/* [
xah_range(min, max) → return a array from min to max, inclusive.
xah_range(min, max, step) → in steps of step.
if step is not integer, then max may not be included
http://xahlee.info/js/javascript_range_array.html
version 2019-04-22
] */
const xah_range = ((min, max , step = 1) => {
    const arr = [];
    const totalSteps = Math.floor((max - min)/step) + 1;
    for (let ii = 0; ii < totalSteps; ii++ ) { arr.push(ii * step + min) }
    return arr;
} );

// test
console.log( xah_range(3, 7) ); // [ 3, 4, 5, 6, 7]
console.log( xah_range(3, 4.5) ); // [ 3, 4]
console.log( xah_range(3.2, 4.5) ); // [ 3.2, 4.2]
console.log( xah_range(3, 5, .25) ); // [ 3, 3.25, 3.5, 3.75, 4, 4.25, 4.5, 4.75, 5 ]
console.log( xah_range(5, 3, -.25) ); // [ 5, 4.75, 4.5, 4.25, 4, 3.75, 3.5, 3.25, 3 ]
console.log( xah_range(3, 5, .7) ); // [ 3, 3.7, 4.4]

JS Array

  1. Understand JS Array
  2. Create Array
  3. Sparse Array
  4. Array-Like Object
  5. Array How-To

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials