[javascript] How to create an array containing 1...N

I'm looking for any alternatives to the below for creating a JavaScript array containing 1 through to N where N is only known at runtime.

var foo = [];

for (var i = 1; i <= N; i++) {
   foo.push(i);
}

To me it feels like there should be a way of doing this without the loop.

This question is related to javascript arrays

The answer is


A little bit simpler than the string variant:

// create range by N
Array(N).join(0).split(0);

// create a range starting with 0 as the value
Array(7).join(0).split(0).map((v, i) => i + 1) // [1, 2, 3, 4, 5, 6, 7]

Update (1/4/2018): Updated to address the exact OP question. Thanks @lessless for calling this out!


I found this old thread because I was wondering about the same myself, but I guess none of the answers here were easier than your original example as Kokodoko commented, haha!

I ended up using this method myself:

var foo = [];
while (foo.length < N)
    foo.push( foo.length + 1 );

Which is at least slightly faster to type out than a regular for-loop, and hopefully not error-prone (though it might be more expensive computational-wise).

Can even do something like:

var foo= [];
while (foo.length < N)
    foo.push( foo.length%4 + 1 );

to fill the array with 1-4 multiple times in sequential order. Or use this method to fill the array with a single item, though I guess in that case it might be faster to just use Array(N).fill(x).


The least codes I could produce:

for(foo=[x=100]; x; foo[x-1]=x--);
console.log(foo);

Fast

This solution is probably fastest it is inspired by lodash _.range function (but my is simpler and faster)

_x000D_
_x000D_
let N=10, i=0, a=Array(N);

while(i<N) a[i++]=i;



console.log(a);
_x000D_
_x000D_
_x000D_

Performance advantages over current (2020.12.11) existing answers based on while/for

  • memory is allocated once at the beginning by a=Array(N)
  • increasing index i++ is used - which looks is about 30% faster than decreasing index i-- (probably because CPU cache memory faster in forward direction)

Speed tests with more than 20 other solutions was conducted in this answer


In ES6 you can do:

Array(N).fill().map((e,i)=>i+1);

http://jsbin.com/molabiluwa/edit?js,console

Edit: Changed Array(45) to Array(N) since you've updated the question.

_x000D_
_x000D_
console.log(_x000D_
  Array(45).fill(0).map((e,i)=>i+1)_x000D_
);
_x000D_
_x000D_
_x000D_


This question has a lot of complicated answers, but a simple one-liner:

[...Array(255).keys()].map(x => x + 1)

Also, although the above is short (and neat) to write, I think the following is a bit faster (for a max length of:

127, Int8,

255, Uint8,

32,767, Int16,

65,535, Uint16,

2,147,483,647, Int32,

4,294,967,295, Uint32.

(based on the max integer values), also here's more on Typed Arrays):

(new Uint8Array(255)).map(($,i) => i + 1);

Although this solution is also not so ideal, because it creates two arrays, and uses the extra variable declaration "$" (not sure any way to get around that using this method). I think the following solution is the absolute fastest possible way to do this:

for(var i = 0, arr = new Uint8Array(255); i < arr.length; i++) arr[i] = i + 1;

Anytime after this statement is made, you can simple use the variable "arr" in the current scope;

If you want to make a simple function out of it (with some basic verification):

_x000D_
_x000D_
function range(min, max) {_x000D_
    min = min && min.constructor == Number ? min : 0;_x000D_
    !(max && max.constructor == Number && max > min) && // boolean statements can also be used with void return types, like a one-line if statement._x000D_
        ((max = min) & (min = 0));  //if there is a "max" argument specified, then first check if its a number and if its graeter than min: if so, stay the same; if not, then consider it as if there is no "max" in the first place, and "max" becomes "min" (and min becomes 0 by default)_x000D_
_x000D_
    for(var i = 0, arr = new (_x000D_
        max < 128 ? Int8Array : _x000D_
        max < 256 ? Uint8Array :_x000D_
        max < 32768 ? Int16Array : _x000D_
        max < 65536 ? Uint16Array :_x000D_
        max < 2147483648 ? Int32Array :_x000D_
        max < 4294967296 ? Uint32Array : _x000D_
        Array_x000D_
    )(max - min); i < arr.length; i++) arr[i] = i + min;_x000D_
    return arr;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
//and you can loop through it easily using array methods if you want_x000D_
range(1,11).forEach(x => console.log(x));_x000D_
_x000D_
//or if you're used to pythons `for...in` you can do a similar thing with `for...of` if you want the individual values:_x000D_
for(i of range(2020,2025)) console.log(i);_x000D_
_x000D_
//or if you really want to use `for..in`, you can, but then you will only be accessing the keys:_x000D_
_x000D_
for(k in range(25,30)) console.log(k);_x000D_
_x000D_
console.log(_x000D_
    range(1,128).constructor.name,_x000D_
    range(200).constructor.name,_x000D_
    range(400,900).constructor.name,_x000D_
    range(33333).constructor.name,_x000D_
    range(823, 100000).constructor.name,_x000D_
    range(10,4) // when the "min" argument is greater than the "max", then it just considers it as if there is no "max", and the new max becomes "min", and "min" becomes 0, as if "max" was never even written_x000D_
);
_x000D_
_x000D_
_x000D_


so, with the above function, the above super-slow "simple one-liner" becomes the super-fast, even-shorter:

range(1,14000);

ES6 solution using recursion. Different than all other solutions

const range = (n, A = []) => (n === 1) ? [n, ...A] : range(n - 1, [n, ...A]);


console.log(range(5));

for(var i,a=[i=0];i<10;a[i++]=i);

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


for me this is more useful utility:

/**
 * create an array filled with integer numbers from base to length
 * @param {number} from
 * @param {number} to
 * @param {number} increment
 * @param {Array} exclude
 * @return {Array}
 */
export const count = (from = 0, to = 1, increment = 1, exclude = []) => {
  const array = [];
  for (let i = from; i <= to; i += increment) !exclude.includes(i) && array.push(i);
  return array;
};

You can use this:

new Array(/*any number which you want*/)
    .join().split(',')
    .map(function(item, index){ return ++index;})

for example

new Array(10)
    .join().split(',')
    .map(function(item, index){ return ++index;})

will create following array:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

'_'.repeat(5).split('').map((_, i) => i + 1) will yield [1, 2, 3, 4, 5]


Iterable version using a generator function that doesn't modify Number.prototype.

_x000D_
_x000D_
function sequence(max, step = 1) {_x000D_
  return {_x000D_
    [Symbol.iterator]: function* () {_x000D_
      for (let i = 1; i <= max; i += step) yield i_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log([...sequence(10)])
_x000D_
_x000D_
_x000D_


ES5 version, inefficient, but perhaps the shortest one that's an expression, not some statement where a variable is populated with eg. a for loop:

(Array(N)+'').split(',').map(function(d,i){return i})

Here is the summary (run in console):

// setup:
var n = 10000000;
function* rangeIter(a, b) {
    for (let i = a; i <= b; ++i) yield i;
}
function range(n) { 
    let a = []
    for (; n--; a[n] = n);
    return a;
}
function sequence(max, step = 1) {
    return {
        [Symbol.iterator]: function* () {
            for (let i = 1; i <= max; i += step) yield i
        }
    }
}

var t0, t1, arr;
// tests
t0 = performance.now();
arr = Array.from({ length: n }, (a, i) => 1)
t1 = performance.now();
console.log("Array.from({ length: n }, (a, i) => 1) Took " + (t1 - t0) + " milliseconds.");

t0 = performance.now();
arr = range(n);
t1 = performance.now();
console.log("range(n) Took " + (t1 - t0) + " milliseconds.");

t0 = performance.now();
arr = Array.from(rangeIter(0, n));
t1 = performance.now();
console.log("Array.from(rangeIter(0, n)) Took " + (t1 - t0) + " milliseconds.");

t0 = performance.now();
arr = [...rangeIter(0, n)];
t1 = performance.now();
console.log("[...rangeIter(0, n)] Took " + (t1 - t0) + " milliseconds.");

t0 = performance.now();
arr = Array.from(sequence(n));
t1 = performance.now();
console.log("Array.from(sequence(n)) Took " + (t1 - t0) + " milliseconds.");

t0 = performance.now();
arr = [...sequence(n)];
t1 = performance.now();
console.log("[...sequence(n)] Took " + (t1 - t0) + " milliseconds.");

t0 = performance.now();
arr = Array(n).fill(0).map(Number.call, Number);
t1 = performance.now();
console.log("Array(n).fill(0).map(Number.call, Number) Took " + (t1 - t0) + " milliseconds.");

t0 = performance.now();
arr = Array.from(Array(n).keys());
t1 = performance.now();
console.log("Array.from(Array(n).keys()) Took " + (t1 - t0) + " milliseconds.");

t0 = performance.now();
arr = [...Array(n).keys()];
t1 = performance.now();
console.log("[...Array(n).keys()] Took " + (t1 - t0) + " milliseconds.");

The fastest is Array(n).fill(0).map(Number.call, Number), 2nd is [...Array(n).keys()]

But '...rangeIter' way is quite handy (can be inlined), fast and more powerful


All of these are too complicated. Just do:

function count(num) {
  var arr = [];
  var i = 0;

  while (num--) {
    arr.push(i++);
  }

  return arr;
}

console.log(count(9))
//=> [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]

Or to do a range from a to b

function range(a, b) {
  var arr = [];

  while (a < b + 1) {
    arr.push(a++);
  }

  return arr;
}

console.log(range(4, 9))
//=> [ 4, 5, 6, 7, 8, 9 ]

function range(start, end) {
    var foo = [];
    for (var i = start; i <= end; i++) {
        foo.push(i);
    }
    return foo;
}

Then called by

var foo = range(1, 5);

There is no built-in way to do this in Javascript, but it's a perfectly valid utility function to create if you need to do it more than once.

Edit: In my opinion, the following is a better range function. Maybe just because I'm biased by LINQ, but I think it's more useful in more cases. Your mileage may vary.

function range(start, count) {
    if(arguments.length == 1) {
        count = start;
        start = 0;
    }

    var foo = [];
    for (var i = 0; i < count; i++) {
        foo.push(start + i);
    }
    return foo;
}

If you are using lodash, you can use _.range:

_.range([start=0], end, [step=1])

Creates an array of numbers (positive and/or negative) progressing from start up to, but not including, end. A step of -1 is used if a negative start is specified without an end or step. If end is not specified, it's set to start with start then set to 0.

Examples:

_.range(4);
// ? [0, 1, 2, 3]

_.range(-4);
// ? [0, -1, -2, -3]

_.range(1, 5);
// ? [1, 2, 3, 4]

_.range(0, 20, 5);
// ? [0, 5, 10, 15]

_.range(0, -4, -1);
// ? [0, -1, -2, -3]

_.range(1, 4, 0);
// ? [1, 1, 1]

_.range(0);
// ? []

For small ranges a slice is nice. N is only known at runtime, so:

[0, 1, 2, 3, 4, 5].slice(0, N+1)

This is probably the fastest way to generate an array of numbers

Shortest

var a=[],b=N;while(b--)a[b]=b+1;

Inline

var arr=(function(a,b){while(a--)b[a]=a;return b})(10,[]);
//arr=[0,1,2,3,4,5,6,7,8,9]

If you want to start from 1

var arr=(function(a,b){while(a--)b[a]=a+1;return b})(10,[]);
//arr=[1,2,3,4,5,6,7,8,9,10]

Want a function?

function range(a,b,c){c=[];while(a--)c[a]=a+b;return c}; //length,start,placeholder
var arr=range(10,5);
//arr=[5,6,7,8,9,10,11,12,13,14]

WHY?

  1. while is the fastest loop

  2. Direct setting is faster than push

  3. [] is faster than new Array(10)

  4. it's short... look the first code. then look at all other functions in here.

If you like can't live without for

for(var a=[],b=7;b>0;a[--b]=b+1); //a=[1,2,3,4,5,6,7]

or

for(var a=[],b=7;b--;a[b]=b+1); //a=[1,2,3,4,5,6,7]

Final Summary report .. Drrruummm Rolll -

This is the shortest code to generate an Array of size N (here 10) without using ES6. Cocco's version above is close but not the shortest.

(function(n){for(a=[];n--;a[n]=n+1);return a})(10)

But the undisputed winner of this Code golf(competition to solve a particular problem in the fewest bytes of source code) is Niko Ruotsalainen . Using Array Constructor and ES6 spread operator . (Most of the ES6 syntax is valid typeScript, but following is not. So be judicious while using it)

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

to get array with n random numbers between min, max (not unique though)

function callItWhatYouWant(n, min, max) {
    return Array.apply(null, {length: n}).map(Function.call, function(){return Math.floor(Math.random()*(max-min+1)+min)})
}

You can use Array fill and map from Es6; just like some few people suggested in the answers they gave for this question. Below are some few examples:

Example-One: Array(10).fill(0).map((e,i)=>i+1)

Result-One: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Example-Two: Array(100/10).fill(0).map((e,i)=>(i*10)+10)

Result-Two:[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

I prefer this because I find it straight forward and easier.


Try this

const foo = numberOfItems=> [...Array(numberOfItems).keys()].map(i => i+1);

As there are a lot of good answers this might be an option as well, you can also create a function with the below and it will work for any combination of numbers

const start = 10;
const end = 30;    
const difference = Math.abs(start-end);
const rangeArray = new Array(difference + 1).fill(undefined).map((val, key) => {
    return start > end ? start - key : start + key;
})

There is small function, it allow to use construction like [1, 2].range(3, 4) -> [1, 2, 3, 4] also it works with negative params. Enjoy.

Array.prototype.range = function(from, to)
{
   var range = (!to)? from : Math.abs(to - from) + 1, increase = from < to;
   var tmp = Array.apply(this, {"length": range}).map(function()
      {
         return (increase)?from++ : from--;
      }, Number);

   return this.concat(tmp);
};

Answered in Feb 2021

Very simple and easy to generate exactly 1 - N

_x000D_
_x000D_
const n = 10;
const [, ...result] = Array(n + 1).keys();

console.log('Result:', result);
_x000D_
_x000D_
_x000D_


Arrays innately manage their lengths. As they are traversed, their indexes can be held in memory and referenced at that point. If a random index needs to be known, the indexOf method can be used.


This said, for your needs you may just want to declare an array of a certain size:

var foo = new Array(N);   // where N is a positive integer

/* this will create an array of size, N, primarily for memory allocation, 
   but does not create any defined values

   foo.length                                // size of Array
   foo[ Math.floor(foo.length/2) ] = 'value' // places value in the middle of the array
*/


ES6

Spread

Making use of the spread operator (...) and keys method, enables you to create a temporary array of size N to produce the indexes, and then a new array that can be assigned to your variable:

var foo = [ ...Array(N).keys() ];

Fill/Map

You can first create the size of the array you need, fill it with undefined and then create a new array using map, which sets each element to the index.

var foo = Array(N).fill().map((v,i)=>i);

Array.from

This should be initializing to length of size N and populating the array in one pass.

Array.from({ length: N }, (v, i) => i)



In lieu of the comments and confusion, if you really wanted to capture the values from 1..N in the above examples, there are a couple options:

  1. if the index is available, you can simply increment it by one (e.g., ++i).
  2. in cases where index is not used -- and possibly a more efficient way -- is to create your array but make N represent N+1, then shift off the front.

    So if you desire 100 numbers:

    let arr; (arr=[ ...Array(101).keys() ]).shift()
    





Try adding an iterator to Number's prototype.

Number.prototype[Symbol.iterator] = function *(){
  let i = 0;
  while(i < this) yield i++;
  return;
}

Now that numbers are iterable, simply pass a number to Array.from

Array.from(10);//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

or anywhere else an iterable is required, like for...of loops.

for(const number of 10) console.log(number);//logs 0 through 9 sequentially

It's somewhat convoluted, but also cool.


Let's share mine :p

Math.pow(2, 10).toString(2).split('').slice(1).map((_,j) => ++j)

Array(8).fill(0).map(Number.call, Number)

Stealing Igors Number.call trick but using fill() to shorten slightly. Only works with ES6 and above.


function arrGen(n) {
  var a = Array(n)
  while (n--) a[n] = n
  return a
}
// arrGen(10) => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Just for fun, I wanted to build off of Ian Henry's answer.

Of course var array = new Array(N); will give you an array of size N, but the keys and values will be identical.... then to shorten the array to size M, use array.length = M.... but for some added functionality try:

function range()
{
    // This function takes optional arguments:
    // start, end, increment
    //    start may be larger or smaller than end
    // Example:  range(null, null, 2);

    var array = []; // Create empty array

      // Get arguments or set default values:
    var start = (arguments[0] ? arguments[0] : 0);
    var end   = (arguments[1] ? arguments[1] : 9);
      // If start == end return array of size 1
    if (start == end) { array.push(start); return array; }
    var inc   = (arguments[2] ? Math.abs(arguments[2]) : 1);

    inc *= (start > end ? -1 : 1); // Figure out which direction to increment.

      // Loop ending condition depends on relative sizes of start and end
    for (var i = start; (start < end ? i <= end : i >= end) ; i += inc)
        array.push(i);

    return array;
}

var foo = range(1, -100, 8.5)

for(var i=0;i<foo.length;i++){
  document.write(foo[i] + ' is item: ' + (i+1) + ' of ' + foo.length + '<br/>'); 
}?

Output of the above:

1 is item: 1 of 12
-7.5 is item: 2 of 12
-16 is item: 3 of 12
-24.5 is item: 4 of 12
-33 is item: 5 of 12
-41.5 is item: 6 of 12
-50 is item: 7 of 12
-58.5 is item: 8 of 12
-67 is item: 9 of 12
-75.5 is item: 10 of 12
-84 is item: 11 of 12
-92.5 is item: 12 of 12

jsFiddle example

This function makes use of the automatically generated arguments array.

The function creates an array filled with values beginning at start and ending at end with increments of size increment, where

range(start, end, increment);

Each value has a default and the sign of the increment doesn't matter, since the direction of incrementation depends on the relative sizes of start and end.


with ES6 you can do:

// `n` is the size you want to initialize your array
// `null` is what the array will be filled with (can be any other value)
Array(n).fill(null)

Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from


Just another ES6 version.

By making use of Array.from second optional argument:

Array.from(arrayLike[, mapFn[, thisArg]])

We can build the numbered array from the empty Array(10) positions:

Array.from(Array(10), (_, i) => i)

_x000D_
_x000D_
var arr = Array.from(Array(10), (_, i) => i);_x000D_
document.write(arr);
_x000D_
_x000D_
_x000D_


It seems the only flavor not currently in this rather complete list of answers is one featuring a generator; so to remedy that:

const gen = N => [...(function*(){let i=0;while(i<N)yield i++})()]

which can be used thus:

gen(4) // [0,1,2,3]

The nice thing about this is you don't just have to increment... To take inspiration from the answer @igor-shubin gave, you could create an array of randoms very easily:

const gen = N => [...(function*(){let i=0;
  while(i++<N) yield Math.random()
})()]

And rather than something lengthy operationally expensive like:

const slow = N => new Array(N).join().split(',').map((e,i)=>i*5)
// [0,5,10,15,...]

you could instead do:

const fast = N => [...(function*(){let i=0;while(i++<N)yield i*5})()]

You can use a function generator or function* expression. Here's [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function] And a reference to the function generator link to [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function].

let a = 1, b = 10;

function* range(a, b) { for (var i = a; i <= b; ++i) yield i; }

Array.from(range(a, b)); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

[...range(a, b)] // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


The following function returns an array populated with numbers:

var createArrayOfNumbers = function (n) {
    return Array.apply(null, new Array(n)).map(function (empty, index) {
        return index;
    });
};

Note that an array created with the array constructor consists of holes, so it cannot be traversed with array functions like map. Hence using the Array.apply function.


https://stackoverflow.com/a/49577331/8784402

With Delta

For javascript

smallest and one-liner
[...Array(N)].map((v, i) => from + i * step);

Examples and other alternatives

Array.from(Array(10).keys()).map(i => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]

[...Array(10).keys()].map(i => 4 + i * -2);
//=> [4, 2, 0, -2, -4, -6, -8, -10, -12, -14]

Array(10).fill(0).map((v, i) => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]

Array(10).fill().map((v, i) => 4 + i * -2);
//=> [4, 2, 0, -2, -4, -6, -8, -10, -12, -14]

[...Array(10)].map((v, i) => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
Range Function
const range = (from, to, step) =>
  [...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);

range(0, 9, 2);
//=> [0, 2, 4, 6, 8]

// can also assign range function as static method in Array class (but not recommended )
Array.range = (from, to, step) =>
  [...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);

Array.range(2, 10, 2);
//=> [2, 4, 6, 8, 10]

Array.range(0, 10, 1);
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Array.range(2, 10, -1);
//=> []

Array.range(3, 0, -1);
//=> [3, 2, 1, 0]
As Iterators
class Range {
  constructor(total = 0, step = 1, from = 0) {
    this[Symbol.iterator] = function* () {
      for (let i = 0; i < total; yield from + i++ * step) {}
    };
  }
}

[...new Range(5)]; // Five Elements
//=> [0, 1, 2, 3, 4]
[...new Range(5, 2)]; // Five Elements With Step 2
//=> [0, 2, 4, 6, 8]
[...new Range(5, -2, 10)]; // Five Elements With Step -2 From 10
//=>[10, 8, 6, 4, 2]
[...new Range(5, -2, -10)]; // Five Elements With Step -2 From -10
//=> [-10, -12, -14, -16, -18]

// Also works with for..of loop
for (i of new Range(5, -2, 10)) console.log(i);
// 10 8 6 4 2
As Generators Only
const Range = function* (total = 0, step = 1, from = 0) {
  for (let i = 0; i < total; yield from + i++ * step) {}
};

Array.from(Range(5, -2, -10));
//=> [-10, -12, -14, -16, -18]

[...Range(5, -2, -10)]; // Five Elements With Step -2 From -10
//=> [-10, -12, -14, -16, -18]

// Also works with for..of loop
for (i of Range(5, -2, 10)) console.log(i);
// 10 8 6 4 2

// Lazy loaded way
const number0toInf = Range(Infinity);
number0toInf.next().value;
//=> 0
number0toInf.next().value;
//=> 1
// ...

From-To with steps/delta

using iterators
class Range2 {
  constructor(to = 0, step = 1, from = 0) {
    this[Symbol.iterator] = function* () {
      let i = 0,
        length = Math.floor((to - from) / step) + 1;
      while (i < length) yield from + i++ * step;
    };
  }
}
[...new Range2(5)]; // First 5 Whole Numbers
//=> [0, 1, 2, 3, 4, 5]

[...new Range2(5, 2)]; // From 0 to 5 with step 2
//=> [0, 2, 4]

[...new Range2(5, -2, 10)]; // From 10 to 5 with step -2
//=> [10, 8, 6]
using Generators
const Range2 = function* (to = 0, step = 1, from = 0) {
  let i = 0,
    length = Math.floor((to - from) / step) + 1;
  while (i < length) yield from + i++ * step;
};

[...Range2(5, -2, 10)]; // From 10 to 5 with step -2
//=> [10, 8, 6]

let even4to10 = Range2(10, 2, 4);
even4to10.next().value;
//=> 4
even4to10.next().value;
//=> 6
even4to10.next().value;
//=> 8
even4to10.next().value;
//=> 10
even4to10.next().value;
//=> undefined

For Typescript

class _Array<T> extends Array<T> {
  static range(from: number, to: number, step: number): number[] {
    return Array.from(Array(Math.floor((to - from) / step) + 1)).map(
      (v, k) => from + k * step
    );
  }
}
_Array.range(0, 9, 1);

_x000D_
_x000D_
Array(...Array(9)).map((_, i) => i);_x000D_
_x000D_
console.log(Array(...Array(9)).map((_, i) => i))
_x000D_
_x000D_
_x000D_


Performance

Today 2020.12.11 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v83 for chosen solutions.

Results

For all browsers

  • solution O (based on while) is fastest (except Firefox for big N - but it's fast there)
  • solution T is fastest on Firefox for big N
  • solutions M,P are fast for small N
  • solution V (lodash) is fast for big N
  • solution W,X are slow for small N
  • solution F is slow

enter image description here

Details

I perform 2 tests cases:

  • for small N = 10 - you can run it HERE
  • for big N = 1000000 - you can run it HERE

Below snippet presents all tested solutions A B C D E F G H I J K L M N O P Q R S T U V W X

_x000D_
_x000D_
function A(N) {
  return Array.from({length: N}, (_, i) => i + 1)
}

function B(N) {
  return Array(N).fill().map((_, i) => i+1);
}

function C(N) {
  return Array(N).join().split(',').map((_, i) => i+1 );
}

function D(N) {
  return Array.from(Array(N), (_, i) => i+1)
}

function E(N) {
  return Array.from({ length: N }, (_, i) => i+1)
}

function F(N) {
  return Array.from({length:N}, Number.call, i => i + 1)
}

function G(N) {
  return (Array(N)+'').split(',').map((_,i)=> i+1)
}

function H(N) {
  return [ ...Array(N).keys() ].map( i => i+1);
}

function I(N) {
  return [...Array(N).keys()].map(x => x + 1);
}

function J(N) {
  return [...Array(N+1).keys()].slice(1)
}

function K(N) {
  return [...Array(N).keys()].map(x => ++x);
}

function L(N) {
  let arr; (arr=[ ...Array(N+1).keys() ]).shift();
  return arr;
}

function M(N) {
  var arr = [];
  var i = 0;

  while (N--) arr.push(++i);

  return arr; 
}

function N(N) {
  var a=[],b=N;while(b--)a[b]=b+1;
  return a;
}

function O(N) {
  var a=Array(N),b=0;
  while(b<N) a[b++]=b;
  return a;
}

function P(N) {
  var foo = [];
  for (var i = 1; i <= N; i++) foo.push(i);
  return foo;
}

function Q(N) {
  for(var a=[],b=N;b--;a[b]=b+1);
  return a;
}

function R(N) {
  for(var i,a=[i=0];i<N;a[i++]=i);
  return a;
}

function S(N) {
    let foo,x;
    for(foo=[x=N]; x; foo[x-1]=x--);
  return foo;
}

function T(N) {
  return new Uint8Array(N).map((item, i) => i + 1);
}

function U(N) {
  return '_'.repeat(5).split('').map((_, i) => i + 1);
}

function V(N) {
  return _.range(1, N+1);
}

function W(N) {
  return [...(function*(){let i=0;while(i<N)yield ++i})()]
}

function X(N) {
  function sequence(max, step = 1) {
    return {
      [Symbol.iterator]: function* () {
        for (let i = 1; i <= max; i += step) yield i
      }
    }
  }

  return [...sequence(N)];
}


[A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X].forEach(f=> {
  console.log(`${f.name} ${f(5)}`);
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
  
This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
_x000D_
_x000D_

And here are example results for chrome

enter image description here


Improvising on the above:

var range = function (n) {
  return Array(n).join().split(',').map(function(e, i) { return i; });
}  

one can get the following options:

1) Array.init to value v

var arrayInitTo = function (n,v) {
  return Array(n).join().split(',').map(function() { return v; });
}; 

2) get a reversed range:

var rangeRev = function (n) {
  return Array(n).join().split(',').map(function() { return n--; });
};

Based on high voted answer and its high voted comment.

const range = (from, to) => [...Array(to + 1).keys()].slice(from);

// usage
let test = [];
test = range(5, 10);
console.log(test); // output: [ 5, 6, 7, 8, 9, 10 ]

You can do so:

var N = 10; 
Array.apply(null, {length: N}).map(Number.call, Number)

result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

or with random values:

Array.apply(null, {length: N}).map(Function.call, Math.random)

result: [0.7082694901619107, 0.9572225909214467, 0.8586748542729765, 0.8653848143294454, 0.008339877473190427, 0.9911756622605026, 0.8133423360995948, 0.8377588465809822, 0.5577575915958732, 0.16363654541783035]

Explanation

First, note that Number.call(undefined, N) is equivalent to Number(N), which just returns N. We'll use that fact later.

Array.apply(null, [undefined, undefined, undefined]) is equivalent to Array(undefined, undefined, undefined), which produces a three-element array and assigns undefined to each element.

How can you generalize that to N elements? Consider how Array() works, which goes something like this:

function Array() {
    if ( arguments.length == 1 &&
         'number' === typeof arguments[0] &&
         arguments[0] >= 0 && arguments &&
         arguments[0] < 1 << 32 ) {
        return [ … ];  // array of length arguments[0], generated by native code
    }
    var a = [];
    for (var i = 0; i < arguments.length; i++) {
        a.push(arguments[i]);
    }
    return a;
}

Since ECMAScript 5, Function.prototype.apply(thisArg, argsArray) also accepts a duck-typed array-like object as its second parameter. If we invoke Array.apply(null, { length: N }), then it will execute

function Array() {
    var a = [];
    for (var i = 0; i < /* arguments.length = */ N; i++) {
        a.push(/* arguments[i] = */ undefined);
    }
    return a;
}

Now we have an N-element array, with each element set to undefined. When we call .map(callback, thisArg) on it, each element will be set to the result of callback.call(thisArg, element, index, array). Therefore, [undefined, undefined, …, undefined].map(Number.call, Number) would map each element to (Number.call).call(Number, undefined, index, array), which is the same as Number.call(undefined, index, array), which, as we observed earlier, evaluates to index. That completes the array whose elements are the same as their index.

Why go through the trouble of Array.apply(null, {length: N}) instead of just Array(N)? After all, both expressions would result an an N-element array of undefined elements. The difference is that in the former expression, each element is explicitly set to undefined, whereas in the latter, each element was never set. According to the documentation of .map():

callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

Therefore, Array(N) is insufficient; Array(N).map(Number.call, Number) would result in an uninitialized array of length N.

Compatibility

Since this technique relies on behaviour of Function.prototype.apply() specified in ECMAScript 5, it will not work in pre-ECMAScript 5 browsers such as Chrome 14 and Internet Explorer 9.


I would do it this way using ...Array(N).keys()

_x000D_
_x000D_
var foo = [...Array(5).keys()].map(foo => foo + 1)

console.log(foo)
_x000D_
_x000D_
_x000D_


There is another way in ES6, using Array.from which takes 2 arguments, the first is an arrayLike (in this case an object with length property), and the second is a mapping function (in this case we map the item to its index)

Array.from({length:10}, (v,i) => i)

this is shorter and can be used for other sequences like generating even numbers

Array.from({length:10}, (v,i) => i*2)

Also this has better performance than most other ways because it only loops once through the array. Check the snippit for some comparisons

_x000D_
_x000D_
// open the dev console to see results_x000D_
_x000D_
count = 100000_x000D_
_x000D_
console.time("from object")_x000D_
for (let i = 0; i<count; i++) {_x000D_
  range = Array.from({length:10}, (v,i) => i )_x000D_
}_x000D_
console.timeEnd("from object")_x000D_
_x000D_
console.time("from keys")_x000D_
for (let i =0; i<count; i++) {_x000D_
  range = Array.from(Array(10).keys())_x000D_
}_x000D_
console.timeEnd("from keys")_x000D_
_x000D_
console.time("apply")_x000D_
for (let i = 0; i<count; i++) {_x000D_
  range = Array.apply(null, { length: 10 }).map(function(element, index) { return index; })_x000D_
}_x000D_
console.timeEnd("apply")
_x000D_
_x000D_
_x000D_


In ES6:

Array.from({length: 1000}, (_, i) => i).slice(1);

or better yet (without the extra variable _ and without the extra slice call):

Array.from({length:1000}, Number.call, i => i + 1)

Or for slightly faster results, you can use Uint8Array, if your list is shorter than 256 results (or you can use the other Uint lists depending on how short the list is, like Uint16 for a max number of 65535, or Uint32 for a max of 4294967295 etc. Officially, these typed arrays were only added in ES6 though). For example:

Uint8Array.from({length:10}, Number.call, i => i + 1)

ES5:

Array.apply(0, {length: 1000}).map(function(){return arguments[1]+1});

Alternatively, in ES5, for the map function (like second parameter to the Array.from function in ES6 above), you can use Number.call

Array.apply(0,{length:1000}).map(Number.call,Number).slice(1)

Or, if you're against the .slice here also, you can do the ES5 equivalent of the above (from ES6), like:

Array.apply(0,{length:1000}).map(Number.call, Function("i","return i+1"))

Use the very popular Underscore _.range method

// _.range([start], stop, [step])

_.range(10); // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_.range(1, 11); // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_.range(0, 30, 5); // => [0, 5, 10, 15, 20, 25]
_.range(0, -10, -1); //  => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
_.range(0); // => []

Well, simple but important question. Functional JS definitely lacks a generic unfold method under the Array object since we may need to create an array of numeric items not only simple [1,2,3,...,111] but a series resulting from a function, may be like x => x*2 instead of x => x

Currently, to perform this job we have to rely on the Array.prototype.map() method. However in order to use Array.prototype.map() we need to know the size of the array in advance. Well still.. if we don't know the size, then we can utilize Array.prototype.reduce() but Array.prototype.reduce() is intended for reducing (folding) not unfolding right..?

So obviously we need an Array.unfold() tool in functional JS. This is something that we can simply implement ourselves just like;

Array.unfold = function(p,f,t,s){
  var res = [],
   runner = v =>  p(v,res.length-1,res) ? [] : (res.push(f(v)),runner(t(v)), res);
  return runner(s);
};

Arrays.unfold(p,f,t,v) takes 4 arguments.

  • p This is a function which defines where to stop. The p function takes 3 arguments like many array functors do. The value, the index and the currently resulting array. It shall return a Boolean value. When it returns a true the recursive iteration stops.
  • f This is a function to return the next items functional value.
  • t This is a function to return the next argument to feed to f in the next turn.
  • s Is the seed value that will be used to calculate the comfortable seat of index 0 by f.

So if we intend to create an array filled with a series like 1,4,9,16,25...n^2 we can simply do like.

_x000D_
_x000D_
Array.unfold = function(p,f,t,s){_x000D_
  var res = [],_x000D_
   runner = v =>  p(v,res.length-1,res) ? [] : (res.push(f(v)),runner(t(v)), res);_x000D_
  return runner(s);_x000D_
};_x000D_
_x000D_
var myArr = Array.unfold((_,i) => i >= 9, x => Math.pow(x,2), x => x+1, 1);_x000D_
console.log(myArr);
_x000D_
_x000D_
_x000D_


I was looking for a functional solution and I ended up with:

function numbers(min, max) {
  return Array(max-min+2).join().split(',').map(function(e, i) { return min+i; });
}

console.log(numbers(1, 9));

Note: join().split(',') transforms the sparse array into a contiguous one.


I didn't see any solution based on recursive functions (and never wrote recursive functions myself) so here is my try.

Note that array.push(something) returns the new length of the array:

(a=[]).push(a.push(a.push(0))) //  a = [0, 1, 2]

And with a recursive function:

var a = (function f(s,e,a,n){return ((n?n:n=s)>e)?a:f(s,e,a?a:a=[],a.push(n)+s)})(start,end) // e.g., start = 1, end = 5

EDIT : two other solutions

var a = Object.keys(new Int8Array(6)).map(Number).slice(1)

and

var a = []
var i=setInterval(function(){a.length===5?clearInterval(i):a.push(a.length+1)}) 

var foo = Array.from(Array(N), (v, i) => i + 1);


Using new Array methods and => function syntax from ES6 standard (only Firefox at the time of writing).

By filling holes with undefined:

Array(N).fill().map((_, i) => i + 1);

Array.from turns "holes" into undefined so Array.map works as expected:

Array.from(Array(5)).map((_, i) => i + 1)

the new way to filling Array is:

_x000D_
_x000D_
const array = [...Array(5).keys()]_x000D_
console.log(array)
_x000D_
_x000D_
_x000D_

result will be: [0, 1, 2, 3, 4]


Multiple ways using ES6

Using spread operator (...) and keys method

[ ...Array(N).keys() ].map( i => i+1);

Fill/Map

Array(N).fill().map((_, i) => i+1);

Array.from

Array.from(Array(N), (_, i) => i+1)

Array.from and { length: N } hack

Array.from({ length: N }, (_, i) => i+1)

Note about generalised form

All the forms above can produce arrays initialised to pretty much any desired values by changing i+1 to expression required (e.g. i*2, -i, 1+i*2, i%2 and etc). If expression can be expressed by some function f then the first form becomes simply

[ ...Array(N).keys() ].map(f)

Examples:

Array.from({length: 5}, (v, k) => k+1); 
// [1,2,3,4,5]

Since the array is initialized with undefined on each position, the value of v will be undefined

Example showcasing all the forms

_x000D_
_x000D_
let demo= (N) => {_x000D_
  console.log(_x000D_
    [ ...Array(N).keys() ].map(( i) => i+1),_x000D_
    Array(N).fill().map((_, i) => i+1) ,_x000D_
    Array.from(Array(N), (_, i) => i+1),_x000D_
    Array.from({ length: N }, (_, i) => i+1)_x000D_
  )_x000D_
}_x000D_
_x000D_
demo(5)
_x000D_
_x000D_
_x000D_

More generic example with custom initialiser function f i.e.

[ ...Array(N).keys() ].map((i) => f(i))

or even simpler

[ ...Array(N).keys() ].map(f)

_x000D_
_x000D_
let demo= (N,f) => {_x000D_
  console.log(_x000D_
    [ ...Array(N).keys() ].map(f),_x000D_
    Array(N).fill().map((_, i) => f(i)) ,_x000D_
    Array.from(Array(N), (_, i) => f(i)),_x000D_
    Array.from({ length: N }, (_, i) => f(i))_x000D_
  )_x000D_
}_x000D_
_x000D_
demo(5, i=>2*i+1)
_x000D_
_x000D_
_x000D_


The question was for alternatives to this technique but I wanted to share the faster way of doing this. It's nearly identical to the code in the question but it allocates memory instead of using push:

function range(n) {
    let a = Array(n);
    for (let i = 0; i < n; a[i++] = i);
    return a;
}

Array.prototype.fill()

a = Object.keys( [].fill.call({length:7}, '' ) ).map(Number)
a.pop();
console.debug(a)

[0, 1, 2, 3, 4, 5, 6]


_x000D_
_x000D_
// A solution where you do not allocate a N sized array (ES6, with some flow annotation):_x000D_
function* zeroToN(N /* : number */)/* : Generator<number, void, empty> */ {_x000D_
  for (let n = 0; n <= N; n += 1) yield n;_x000D_
}_x000D_
_x000D_
// With this generation, you can have your array_x000D_
console.log([...zeroToN(10-1)])_x000D_
_x000D_
// but let's define a helper iterator function_x000D_
function mapIterator(iterator, mapping) {_x000D_
  const arr = [];_x000D_
  for (let result = iterator.next(); !result.done; result = iterator.next()) {_x000D_
    arr.push(mapping(result.value));_x000D_
  }_x000D_
  return arr;_x000D_
}_x000D_
_x000D_
// now you have a map function, without allocating that 0...N-1 array_x000D_
_x000D_
console.log(mapIterator(zeroToN(10-1), n => n*n));
_x000D_
_x000D_
_x000D_


Using ES2015/ES6 spread operator

[...Array(10)].map((_, i) => i + 1)

_x000D_
_x000D_
console.log([...Array(10)].map((_, i) => i + 1))
_x000D_
_x000D_
_x000D_


Using ES6

const generateArray = n => [...Array(n)].map((_, index) => index + 1);

If you happen to be using d3.js in your app as I am, D3 provides a helper function that does this for you.

So to get an array from 0 to 4, it's as easy as:

d3.range(5)
[0, 1, 2, 3, 4]

and to get an array from 1 to 5, as you were requesting:

d3.range(1, 5+1)
[1, 2, 3, 4, 5]

Check out this tutorial for more info.


Try this:

var foo = [1, 2, 3, 4, 5];

If you are using CoffeeScript, you can create a range by doing:

var foo = [1..5]; 

Otherwise, if you are using vanilla JavaScript, you'll have to use a loop if you want to initialize an array up to a variable length.


the fastest way to fill an Array in v8 is:

[...Array(5)].map((_,i) => i);

result will be: [0, 1, 2, 3, 4]


Object.keys(Array.apply(0, Array(3))).map(Number)

Returns [0, 1, 2]. Very similar to Igor Shubin's excellent answer, but with slightly less trickery (and one character longer).

Explanation:

  • Array(3) // [undefined × 3] Generate an array of length n=3. Unfortunately this array is almost useless to us, so we have to…
  • Array.apply(0,Array(3)) // [undefined, undefined, undefined] make the array iterable. Note: null's more common as apply's first arg but 0's shorter.
  • Object.keys(Array.apply(0,Array(3))) // ['0', '1', '2'] then get the keys of the array (works because Arrays are the typeof array is an object with indexes for keys.
  • Object.keys(Array.apply(0,Array(3))).map(Number) // [0, 1, 2] and map over the keys, converting strings to numbers.

In ES6 using Array from() and keys() methods.

Array.from(Array(10).keys())
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Shorter version using spread operator.

[...Array(10).keys()]
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Start from 1 by passing map function to Array from(), with an object with a length property:

Array.from({length: 10}, (_, i) => i + 1)
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

no for create array in ES6 solutions

js no for 100 array

1. padStart


// string arr
const arr = [...``.padStart(100, ` `)].map((item, i) => i + 1 + ``);

// (100) ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100"]


// number arr
const arr = [...``.padStart(100, ` `)].map((item, i) => i + 1);

// (100) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]


2. Typed Arrays

Uint8Array

// number arr
const arr = new Uint8Array(100).map((item, i) => i + 1);

// Uint8Array(100) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]

// string arr
const arr = [...new Uint8Array(100).map((item, i) => i + 1)].map((item, i) => i + 1 + ``);

// (100) ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100"]