Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 801
Godders Avatar asked Sep 19 '10 17:09

Godders


People also ask

How do you create an array with 1 N in python?

Use the range() Function to Create a List of Numbers From 1 to N. The range() function is very commonly used in Python. It returns a sequence between two numbers given in the function arguments. The starting number is 0 by default if not specified.

How do you make a number an array?

To create an array of values, you simply add square brackets following the type of the values that will be stored in the array: number[] is the type for a number array. Square brackets are also used to set and get values in an array.

What is N 1 in an array?

Elements in an array are obtained by using a zero-based index. That means the first element is at index 0, the second at index 1, and so on. Therefore, if the array has size N , the last element will be at index N-1 (because it starts with 0 ). Thus the index is in the interval [0, N-1] .


1 Answers

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] 
like image 83
Niko Ruotsalainen Avatar answered Sep 21 '22 10:09

Niko Ruotsalainen