JavaScript arrays allow you to store multiple items in a single object.
You can create an array containing 1 to n in JavaScript using Array.from(Array(10).keys()) statement.
Basic Example
var myArray = Array.from(Array(10).keys());
console.log(myArray); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
This tutorial teaches you how to create an array containing 1 to n in JavaScript and when it is appropriate to use each method.
Using Array From And Keys() Method [ES6]
The array.from() static method creates an array with the items from an array like iterables.
To create an array containing 1..n
using the array.from()
method,
- Pass the
array(n).keys()
to thearray.from()
method - The
keys()
method returns the index of each item as an iterable. This means it will contain items from0
ton
. - To create an array from 1, slice out the first item
0
using theslice(1)
.
Use this method when you want to create an array starting from 1 to N and do not want to increment/step more than once for each item.
Code
var myArray = Array.from(Array(11).keys()).slice(1);
console.log(myArray); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Using Array From and Index
The array.from()
method creates an array from the array like iterables. You can use the arrow function with the array.from()
method and pass the item to create an array.
- Pass the number of items needed in the array
- For items, use the index of each item. You can also increment or decrement the index to create step(s) between each element in the created array
- An array will be created with the index of the items.
Use this method when you want to create an array with numbers of a specific range and increment/decrement each number by 1 or 2, or x.
Code
The following code creates an array with 5
items, and each item is incremented with 2
from the previous items.
var noOfItems = 5;
var myArray = Array.from({
length: noOfItems
},
(_, index) => (index + (index + 2))
);
console.log(myArray) // [2, 4, 6, 8, 10]
Using Spread Operator and Keys() Method [ES6]
The spread […] operator deconstructs the array of items.
To create an array with items from 1 to n,
- Use the
array(n).keys()
method to get the list ofn
keys - Extract the list of keys into an array using the spread
[...]
operator.
Code
var myArray = [...Array(10).keys()];
console.log(myArray); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Using For Loop
For loop executes a set of codes until the condition fails.
To create an array with 1 to n
,
- Use the
for
loop and iterate it until the number of items you need in the array - During each iteration, push the element into the array
This is the simplest method to create an array with N items.
Use this method when you want to create an array with items starting from a number different from 1.
Code
var myArray = [];
const noOfItems = 5;
for (let i = 1; i <= noOfItems; i++) {
myArray.push(i);
}
console.log(myArray); // [1, 2, 3, 4, 5]