How to Create an Array from 1 to n in JavaScript?

Estimated read time 1 min read

To create an array from 1 to n in JavaScript, you can call the Array.from() method and pass it an object that implements the iterable protocol, such as an array-like object with a length property. Here’s an example code snippet that demonstrates how to create an array from 1 to n in JavaScript:

function createArrayFromOneToN(n) {
  return Array.from({ length: n }, (_, index) => index + 1);
}

const newArray = createArrayFromOneToN(5);
console.log(newArray); // [1, 2, 3, 4, 5]

In this code, the createArrayFromOneToN() function takes one argument: n which represents the length of the resulting array.

Inside the function, the Array.from() method is called with an object that has a length property set to n. The second argument is a mapping function that maps each element of the new array to its corresponding index plus one.

The resulting array is then returned from the function, and its value is assigned to a new variable called newArray. We have passed the argument 5 to the createArrayFromOneToN() function to create an array from 1 to 5, and then we log the resulting array to the console.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply