2415

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.

7
  • 418
    After reading this entire page, I have come to the conclusion that your own simple for-loop is the simplest, most readable, and least error-prone.
    – Kokodoko
    Commented May 8, 2014 at 16:09
  • 1
    If anyone needs something more advanced, I created a node.js lib that does this for numbers, letters, negative/positive ranges, etc. github.com/jonschlinkert/fill-range. It's used in github.com/jonschlinkert/braces for brace expansion and github.com/jonschlinkert/micromatch for glob patterns Commented Jun 9, 2015 at 5:21
  • Another way of doing it can be like this : Array.from({length : 10}, (_, v) => v) Commented Aug 25, 2019 at 0:15
  • @SahilGupta Almost. If we want 1 to 10, we need to add 1, e.g. this: Array.from({length : 10}, (_, v) => v+1) Commented Oct 13, 2019 at 21:54
  • Instead of an array, define foo as object {} then add your own indexes with foo[i] = i;
    – SPlatten
    Commented Feb 27, 2020 at 13:42

80 Answers 80

13

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

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

console.log(foo)

13

Thank @NikoRuotsalainen for his/her answer. I wrote this in my utilities:

const range = ({from = 0, to, step = 1, length = Math.ceil((to - from) / step)}) => 
  Array.from({length}, (_, i) => from + i * step)

Examples:

const range = ({from = 0, to, step = 1, length = Math.ceil((to - from) / step)}) => 
  Array.from({length}, (_, i) => from + i * step)

console.log(
  range({length: 5}), // [0, 1, 2, 3, 4]
  range({to: 5}),    // [0, 1, 2, 3, 4]
  range({from: 2, to: 5}),    // [2, 3, 4] (inclusive `from`, exclusive `to`)
  range({from: 2, length: 4}), // [2, 3, 4, 5]
  range({from: 1, to: 5, step: 2}), // [1, 3]
  range({from: 1, to: 6, step: 2}), // [1, 3, 5]
)

12
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.

3
  • This will create a range of numbers from 0 to 7 not from 1 to 8 Commented Jan 5, 2017 at 0:29
  • Shorter is simply: Array(5).fill().map((_, i) => i+1)
    – vsync
    Commented Oct 24, 2020 at 10:06
  • if you want to add 0 to single digit numbers var foo = Array(52).fill().map((v,i)=> { let r = (i+1).toString().length == 1 ? "0" + (i + 1).toString() : (i + 1).toString(); return r } ); Commented Apr 6, 2022 at 7:09
12

You can just do this:

var arr = Array.from(Array(10).keys())
arr.shift()
console.log(arr)

0
11

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.

10

Using ES6

const generateArray = n => [...Array(n)].map((_, index) => index + 1);
2
  • Thanks! This was the most elegant answer in my opinion! One could also use Array.from(Array(n)) if the spread operator is not supported.
    – Amit
    Commented Oct 8, 2017 at 8:36
  • At first I didn't know why you had to use the spread operator, but then I read the following about map on MDN: "It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value)."
    – battmanz
    Commented Feb 9, 2018 at 19:06
10

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)

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

1
  • This is more complicated and ~10x slower than [...Array(11).keys()].slice(1). Commented Sep 13, 2018 at 23:27
10

for start from 1:

[...Array(31).keys()].map(a=>a+1)
1
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
    – mufazmi
    Commented May 21, 2021 at 18:22
9

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

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

console.log([...sequence(10)])

1
9
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

8

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.
8

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]

8

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!

2
  • how to make it starting from 1?
    – lessless
    Commented Mar 27, 2015 at 6:42
  • @lessless you'll have to modify the Map: Array(7).join(0).split(0).map(function (v, i) {return i + 1});
    – Matt Lo
    Commented Mar 29, 2015 at 17:13
8

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

2
  • 4
    Additional context may be helpful to preserve the long-term value of the answer. Please consider adding additional supplementary information to expand on the answer. Commented Jun 16, 2020 at 13:01
  • (v, i) => i + 1 is a map (see MDN), it takes current index and sets the value to be one more than the index - you get [1, 2, 3, 4, 5] if N = 5 — that's a very elegant solution
    – revelt
    Commented Sep 29, 2020 at 7:17
8

Generate 9 items with a step size of 1, starting with 1:

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

Result:

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

Generate 9 items with a step size of 5, starting with 5:

Array(9).fill(5).map((e,i)=>e+(i*5));

Result:

[ 5, 10, 15, 20, 25, 30, 35, 40, 45 ]

Execution, user and system time:

Arr size: 1
Execution Time: 3.731ms
User CPU time: 0.033ms
System CPU time: 0.013ms

Arr size: 10
Execution Time: 3.704ms
User CPU time: 0.031ms
System CPU time: 0.01ms

Arr size: 100
Execution Time: 4.001ms
User CPU time: 0.038ms
System CPU time: 0.013ms

Arr size: 1000
Execution Time: 3.735ms
User CPU time: 0.058ms
System CPU time: 0.014ms

Arr size: 10000
Execution Time: 5.185ms
User CPU time: 0.262ms
System CPU time: 0.098ms

Arr size: 100000
Execution Time: 6.937ms
User CPU time: 3.936ms
System CPU time: 0.363ms

Arr size: 1000000
Execution Time: 24.848ms
User CPU time: 17.657ms
System CPU time: 4.185ms
6

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.

1
  • If you want your array to start with the value of 1, all you got to do is return index +1
    – AllJs
    Commented May 24, 2021 at 7:35
6

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--; });
};
2
  • This answer is perfect for filling a select dropdown in React, Angular or some other framework. Or even just plain vanilla JS.
    – jorisw
    Commented Jul 14, 2016 at 13:14
  • Brilliant answer, very fast and have no problems with very big numbers.
    – gMirian
    Commented Sep 18, 2023 at 9:58
6

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)}) 
1
  • Object.keys(new Int8Array(N)) is a clever hack, and faster than the Array.apply() and Array.from() solutions, but with ES2015, we have a faster and less weird-looking solution, [...Array(11).keys()].slice(1). Commented Sep 13, 2018 at 23:31
6

One can an Int8Array, Int16Array, and Int32Array to create an array ranging from 1 to n like so:

const zeroTo100 = new Int8Array(100).map((curr, index) => curr = index + 1);
/* Int8Array(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]

You can also use the following typed arrays to generate 1 to n items inside of an array.

  1. Uint8Array, Uint16Array, Uint32Array
  2. BigInt64Array
  3. Uint8ClampedArray
  4. FloatArray32, FloatArray64

Of course, you lose the ability to put anything in these arrays besides numbers, so use this small shortcut at your own peril.

Furthermore, if you just need an array with n amount of zeros in it, then just do this:

const arr_100_0s = new Int8Array(100)

Edit: You can use this to quickly generate a range as well like so:

function range(start, end) {
    const arr = new Int8Array(end - start + 1).map((curr, i) => curr + i + start);
    return arr;
}

range(15, 30); // Int8Array(16) [15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]

Not quite what the user asked for, but is highly related IMO.

0
6

Simple range generator:

    const min = 2000;
    const max = 2022;
    const range = Array.from({ length: max - min + 1 }, (v, k) => k + min); 
    console.log('range', range);
6

Legacy Browser Friendly Array Constructor

If you want cross-browser friendly solutions, you still cannot beat the for loop. This one-liner still works in 20+ years of browsers, including Internet Explorer 5-11 (1998-present).

for(var arr=[],i=0;i<10;i++){arr[i]=i+1};

alert(arr);// <<< [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Otherwise, this works in modern HTML5 browsers...

const arr = Array(10).fill().map((v,i)=>++i)

alert(arr);// <<< [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
1
  • Easiest to understand and should have way more up votes!
    – Ken H
    Commented Jul 31 at 15:15
6

const n = 5;
const arrayN = Array(n).fill('fill with anything').map((v,i)=>i);
console.log(arrayN)

5

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.

4
  • 2
    That's a seriously inefficient approach. It creates 3 arrays, a string, and calls a function max - min times. Consider: for (var i=max-min+1, a=[]; i--;) a[i] = min+i; which creates one array and does one loop and is less to write. ;-)
    – RobG
    Commented Aug 9, 2015 at 23:54
  • See stackoverflow.com/questions/12760643/…, Array.prototype.slice.call(new Float32Array (12));
    – Corey Alix
    Commented Nov 11, 2015 at 16:18
  • I was building something similar and settled on return Array((max+1)-min).fill().map((_,i) => i + min);. It dodges the off-by-one issue and works for any number assuming max is bigger than min.
    – rtpHarry
    Commented Mar 7, 2021 at 1:51
  • (im not sure about efficiency, at the moment I'm just trying to write everything in functional form to get used it)
    – rtpHarry
    Commented Mar 7, 2021 at 1:52
4

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 ]
4

Let's share mine :p

Math.pow(2, 10).toString(2).split('').slice(1).map((_,j) => ++j)
1
  • Best one so far! Simple! Precise! Accurate! All in one line... pythonian!
    – rubmz
    Commented Aug 11, 2022 at 7:58
4

most concise i could come up with:

[...''.padEnd(N)].map((_,i)=>i+1)
2
  • In map function what is the _ for?
    – Shweta
    Commented Nov 9, 2022 at 13:09
  • The first parameter is the iterated item, and the second parameter is the index. We don't need the item so the underscore marks that it won't be used. Commented Nov 9, 2022 at 22:04
3

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.

3

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;
}
3

The least codes I could produce:

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

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.

1

Not the answer you're looking for? Browse other questions tagged or ask your own question.