Godders
Godders

Reputation: 24996

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.

Upvotes: 2452

Views: 2751033

Answers (30)

Amir M. Mohamadi
Amir M. Mohamadi

Reputation: 1522

Simply, this worked for me:

[...Array(5)].map(...)

Upvotes: 84

KooiInc
KooiInc

Reputation: 122966

Another idea: statically extend Array with a 'range' Symbol.

See also this Stackblitz snippet.

Example (using a classical loop for the extension function).

const range = Symbol(`range`);
Array[range] = createRange;

console.log(`[${Array[range]({len: 5})}]`);
console.log(`[${Array[range]({len: 5, start: 26})}]`);
console.log(`[${Array[range]({len: 8, start: 32, step: 32})}]`);

function createRange({len = 1, start = 0, step = 1} = {}) {
  const range = []; 

  for (let i = 0; i < len; i += 1) {
    range.push(start + i * step);
  }
  
  return range;
}

Upvotes: 0

Vladimir Djuricic
Vladimir Djuricic

Reputation: 4623

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

Upvotes: 10

ahmnouira
ahmnouira

Reputation: 3481

Example

To generate a string of 1..12 values using the spread operator and adding different elements at the end or at the start.

[
  ...[...Array(12).keys()].map((e) => (e + 1).toString()),
  'hidden',
  'default',
]

/* [
  '1',      '2',
  '3',      '4',
  '5',      '6',
  '7',      '8',
  '9',      '10',
  '11',     '12',
  'hidden', 'default'
]
*/

Upvotes: 1

jen
jen

Reputation: 349

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

Upvotes: 6

Stokely
Stokely

Reputation: 15897

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]

Upvotes: 6

Mo.
Mo.

Reputation: 27503

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);

const arrayStartWithOne = Array.from(Array(10).keys(), item => item + 1);
console.log(arrayStartWithOne)

Upvotes: 49

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92657

Performance

Today 2020.12.11 I performed 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 the fastest (except Firefox for big N - but it's fast there)
  • solution T is fastest on Firefox for big N
  • solutions M,P is 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

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 snippet only presents functions used in performance tests - it does not perform tests itself!

And here are example results for chrome

enter image description here

Upvotes: 78

iGroza
iGroza

Reputation: 929

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);

Upvotes: 6

Bobby Morelli
Bobby Morelli

Reputation: 584

most concise i could come up with:

[...''.padEnd(N)].map((_,i)=>i+1)

Upvotes: 4

Mir-Ismaili
Mir-Ismaili

Reputation: 17184

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

Upvotes: 13

Niko Ruotsalainen
Niko Ruotsalainen

Reputation: 53862

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]

Upvotes: 3933

brff19
brff19

Reputation: 834

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.

Upvotes: 6

scunliffe
scunliffe

Reputation: 63676

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/

Upvotes: 561

Mohammad Daneshamooz
Mohammad Daneshamooz

Reputation: 294

for start from 1:

[...Array(31).keys()].map(a=>a+1)

Upvotes: 10

Belhadjer Samir
Belhadjer Samir

Reputation: 1669

You can just do this:

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

Upvotes: 12

Diamond
Diamond

Reputation: 3448

Very simple and easy to generate exactly 1 - N

const [, ...result] = Array(11).keys();

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

Upvotes: 31

аlex
аlex

Reputation: 5698

Try this one

[...Array.from({length:30}).keys()]

Upvotes: 3

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92657

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 index i-- (probably because CPU cache memory faster in forward direction)

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

Upvotes: 26

nfroidure
nfroidure

Reputation: 1601

Let's share mine :p

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

Upvotes: 5

nkitku
nkitku

Reputation: 5738

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);

Upvotes: 30

xgqfrms
xgqfrms

Reputation: 12206

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

Upvotes: 3

Alexandre Elshobokshy
Alexandre Elshobokshy

Reputation: 10922

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

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

console.log(foo)

Upvotes: 13

dabeng
dabeng

Reputation: 1450

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

Upvotes: 8

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"))

Upvotes: 20

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93481

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

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)

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)

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)

Upvotes: 776

vol7ron
vol7ron

Reputation: 42149

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()
    




Upvotes: 476

Mehdi Dehghani
Mehdi Dehghani

Reputation: 11601

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 ]

Upvotes: 3

Tim
Tim

Reputation: 1072

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

Upvotes: 9

аlex
аlex

Reputation: 5698

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

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

Upvotes: 16

Related Questions