JS: Range Function for Array

By Xah Lee. Date: . Last updated: .

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

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

[…Array(n).keys()]

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

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

[see JS: Spread Operator]

[see JS: Array.prototype.keys]

Range Function for Array

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-04-22
const xah_range = ((min, max , step = 1) => {
    const arr = [];
    const totalSteps = Math.floor((max - min)/step);
    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

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Object Ref
  5. DOM Scripting
  6. SVG
  7. Blog