How to create an array containing 1...N
JavascriptArraysJavascript Problem Overview
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.
Javascript Solutions
Solution 1 - Javascript
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]
Solution 2 - Javascript
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.
Solution 3 - Javascript
ES6
Multiple ways using...
) and keys method
Using spread operator ([ ...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)
{ length: N }
hack
Array.from and 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
let demo= (N) => {
console.log(
[ ...Array(N).keys() ].map(( i) => i+1),
Array(N).fill().map((_, i) => i+1) ,
Array.from(Array(N), (_, i) => i+1),
Array.from({ length: N }, (_, i) => i+1)
)
}
demo(5)
f
i.e.
More generic example with custom initialiser function [ ...Array(N).keys() ].map((i) => f(i))
or even simpler
[ ...Array(N).keys() ].map(f)
let demo= (N,f) => {
console.log(
[ ...Array(N).keys() ].map(f),
Array(N).fill().map((_, i) => f(i)) ,
Array.from(Array(N), (_, i) => f(i)),
Array.from({ length: N }, (_, i) => f(i))
)
}
demo(5, i=>2*i+1)
Solution 4 - Javascript
If I get what you are after, you want an array of numbers 1..n
that you can later loop through.
If this is all you need, can you do this instead?
var foo = new Array(45); // create an empty array with length 45
then when you want to use it... (un-optimized, just for example)
for(var i = 0; i < foo.length; i++){
document.write('Item: ' + (i + 1) + ' of ' + foo.length + '<br/>');
}
e.g. if you don't need to store anything in the array, you just need a container of the right length that you can iterate over... this might be easier.
See it in action here: http://jsfiddle.net/3kcvm/
Solution 5 - Javascript
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:
- if the index is available, you can simply increment it by one (e.g.,
++i
). - 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()
Solution 6 - Javascript
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.
console.log(
Array(45).fill(0).map((e,i)=>i+1)
);
Solution 7 - Javascript
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); // => []
Solution 8 - Javascript
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;
}
Solution 9 - Javascript
the fastest way to fill an Array
in v8 is:
[...Array(5)].map((_,i) => i);
result will be: [0, 1, 2, 3, 4]
Solution 10 - Javascript
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):
function range(min, max) {
min = min && min.constructor == Number ? min : 0;
!(max && max.constructor == Number && max > min) && // boolean statements can also be used with void return types, like a one-line if statement.
((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)
for(var i = 0, arr = new (
max < 128 ? Int8Array :
max < 256 ? Uint8Array :
max < 32768 ? Int16Array :
max < 65536 ? Uint16Array :
max < 2147483648 ? Int32Array :
max < 4294967296 ? Uint32Array :
Array
)(max - min); i < arr.length; i++) arr[i] = i + min;
return arr;
}
//and you can loop through it easily using array methods if you want
range(1,11).forEach(x => console.log(x));
//or if you're used to pythons for...in
you can do a similar thing with for...of
if you want the individual values:
for(i of range(2020,2025)) console.log(i);
//or if you really want to use `for..in`, you can, but then you will only be accessing the keys:
for(k in range(25,30)) console.log(k);
console.log(
range(1,128).constructor.name,
range(200).constructor.name,
range(400,900).constructor.name,
range(33333).constructor.name,
range(823, 100000).constructor.name,
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
);
so, with the above function, the above super-slow "simple one-liner" becomes the super-fast, even-shorter:
range(1,14000);
Solution 11 - Javascript
Using ES2015/ES6 spread operator
[...Array(10)].map((_, i) => i + 1)
console.log([...Array(10)].map((_, i) => i + 1))
Solution 12 - Javascript
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]
Solution 13 - Javascript
If you happen to be using [d3.js][1] 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][2] for more info.
[1]: http://d3js.org/ "D3" [2]: http://www.janwillemtulp.com/2011/03/31/tutorialthe-basics-working-with-arrays-in-d3/
Solution 14 - Javascript
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?
-
while
is the fastest loop -
Direct setting is faster than
push
-
[]
is faster thannew Array(10)
-
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]
Solution 15 - Javascript
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);
// ➜ []
Solution 16 - Javascript
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
Details
I perform 2 tests cases:
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
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)}`);
})
<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!
And here are example results for chrome
Solution 17 - Javascript
the new way to filling Array
is:
const array = [...Array(5).keys()]
console.log(array)
result will be: [0, 1, 2, 3, 4]
Solution 18 - Javascript
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)
Solution 19 - Javascript
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);
Solution 20 - Javascript
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()]
Solution 21 - Javascript
Very simple and easy to generate exactly 1 - N
const [, ...result] = Array(11).keys();
console.log('Result:', result);
Solution 22 - Javascript
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
// open the dev console to see results
count = 100000
console.time("from object")
for (let i = 0; i<count; i++) {
range = Array.from({length:10}, (v,i) => i )
}
console.timeEnd("from object")
console.time("from keys")
for (let i =0; i<count; i++) {
range = Array.from(Array(10).keys())
}
console.timeEnd("from keys")
console.time("apply")
for (let i = 0; i<count; i++) {
range = Array.apply(null, { length: 10 }).map(function(element, index) { return index; })
}
console.timeEnd("apply")
Solution 23 - Javascript
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)
Solution 24 - Javascript
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"))
Solution 25 - Javascript
Fast
This solution is probably fastest it is inspired by lodash _.range function (but my is simpler and faster)
let N=10, i=0, a=Array(N);
while(i<N) a[i++]=i;
console.log(a);
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 indexi--
(probably because CPU cache memory faster in forward direction)
Speed tests with more than 20 other solutions was conducted in this answer
Solution 26 - Javascript
Array(...Array(9)).map((_, i) => i);
console.log(Array(...Array(9)).map((_, i) => i))
Solution 27 - Javascript
for(var i,a=[i=0];i<10;a[i++]=i);
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Solution 28 - Javascript
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})()]
Solution 29 - Javascript
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.
Solution 30 - Javascript
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.
Solution 31 - Javascript
Using ES6
const generateArray = n => [...Array(n)].map((_, index) => index + 1);
Solution 32 - Javascript
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);
Solution 33 - Javascript
I would do it this way using ...Array(N).keys()
var foo = [...Array(5).keys()].map(foo => foo + 1)
console.log(foo)
Solution 34 - Javascript
You can just do this:
var arr = Array.from(Array(10).keys())
arr.shift()
console.log(arr)
Solution 35 - Javascript
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)])
Solution 36 - Javascript
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
Solution 37 - Javascript
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]
)
Solution 38 - Javascript
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!
Solution 39 - Javascript
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.
Solution 40 - Javascript
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]
Solution 41 - Javascript
for start from 1:
[...Array(31).keys()].map(a=>a+1)
Solution 42 - Javascript
var foo = Array.from(Array(N), (v, i) => i + 1);
Solution 43 - Javascript
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.
Solution 44 - Javascript
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)})
Solution 45 - Javascript
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.
Solution 46 - Javascript
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:
-
Array.init to value v
var arrayInitTo = function (n,v) { return Array(n).join().split(',').map(function() { return v; }); };
-
get a reversed range:
var rangeRev = function (n) { return Array(n).join().split(',').map(function() { return n--; }); };
Solution 47 - Javascript
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 ]
Solution 48 - Javascript
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.
- Uint8Array, Uint16Array, Uint32Array
- BigInt64Array
- Uint8ClampedArray
- 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.
Solution 49 - Javascript
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.
Solution 50 - Javascript
Let's share mine :p
Math.pow(2, 10).toString(2).split('').slice(1).map((_,j) => ++j)
Solution 51 - Javascript
The least codes I could produce:
for(foo=[x=100]; x; foo[x-1]=x--);
console.log(foo);
Solution 52 - Javascript
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.
Solution 53 - Javascript
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)
.
Solution 54 - Javascript
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));
Solution 55 - Javascript
Try this
const foo = numberOfItems=> [...Array(numberOfItems).keys()].map(i => i+1);
Solution 56 - Javascript
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 ]
Solution 57 - Javascript
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"]
Solution 58 - Javascript
Try this one
[...Array.from({length:30}).keys()]
Solution 59 - Javascript
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.
Solution 60 - Javascript
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;
}
Solution 61 - Javascript
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]
Solution 62 - Javascript
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})
Solution 63 - Javascript
// A solution where you do not allocate a N sized array (ES6, with some flow annotation):
function* zeroToN(N /* : number */)/* : Generator<number, void, empty> */ {
for (let n = 0; n <= N; n += 1) yield n;
}
// With this generation, you can have your array
console.log([...zeroToN(10-1)])
// but let's define a helper iterator function
function mapIterator(iterator, mapping) {
const arr = [];
for (let result = iterator.next(); !result.done; result = iterator.next()) {
arr.push(mapping(result.value));
}
return arr;
}
// now you have a map function, without allocating that 0...N-1 array
console.log(mapIterator(zeroToN(10-1), n => n*n));
Solution 64 - Javascript
'_'.repeat(5).split('').map((_, i) => i + 1)
will yield [1, 2, 3, 4, 5]
Solution 65 - Javascript
most concise i could come up with:
[...''.padEnd(N)].map((_,i)=>i+1)
Solution 66 - Javascript
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 atrue
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.
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);
};
var myArr = Array.unfold((_,i) => i >= 9, x => Math.pow(x,2), x => x+1, 1);
console.log(myArr);
Solution 67 - Javascript
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;
};
Solution 68 - Javascript
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
Solution 69 - Javascript
Solution for empty array and with just number in array
const arrayOne = new Array(10);
console.log(arrayOne);
const arrayTwo = [...Array(10).keys()];
console.log(arrayTwo);
var arrayThree = Array.from(Array(10).keys());
console.log(arrayThree);
Solution 70 - Javascript
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);
};
Solution 71 - Javascript
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)})
}
Solution 72 - Javascript
For small ranges a slice is nice. N is only known at runtime, so:
[0, 1, 2, 3, 4, 5].slice(0, N+1)
Solution 73 - Javascript
a = Object.keys( [].fill.call({length:7}, '' ) ).map(Number)
a.pop();
console.debug(a)
[0, 1, 2, 3, 4, 5, 6]
Solution 74 - Javascript
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;
})