Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavascriptHow to create an array containing 1…N numbers in JavaScript ?

How to create an array containing 1…N numbers in JavaScript ?

In this article, we will see how to create an array containing 1. . . N numbers using JavaScript. We can create an array by using different methods.

There are some methods to create an array containing 1…N numbers, which are given below:

Method 1: Using for Loop

We can use for loop to create an array containing numbers from 1 to N in JavaScript. The for loop iterates from 1 to N and pushes each number to an array. 

Example:

Javascript




function createArray(N) {
    let newArr = [];
    for (let i = 1; i <= N; i++) {
        newArr.push(i);
    }
    return newArr;
}
 
let N = 12;
let arr = createArray(N);
console.log(arr);


Output

[
   1,  2, 3, 4,  5,
   6,  7, 8, 9, 10,
  11, 12
]



Method 2: Using Spread Operator

We can also use Spread Operator to create an array containing 1…N numbers. We use Array() constructor to create a new array of length N, and then use keys() method to get an iterator over the indices of the array. Then spread the iterator into an array using the spread operator (…) and map each element of the resulting array to its corresponding index value plus 1.

Example:

Javascript




function createArray(N) {
    return [...Array(N).keys()].map(i => i + 1);
}
 
let N = 12;
let arr = createArray(N);
console.log(arr);


Output

[
   1,  2, 3, 4,  5,
   6,  7, 8, 9, 10,
  11, 12
]



Method 3: Using from() Method

We can also use the Array.from() method to create an array containing numbers from 1 to N. 

Example:

Javascript




function createArray(N) {
    return Array.from({length: N}, (_, index) => index + 1);
}
 
let N = 12;
let arr = createArray(N);
console.log(arr);


Output

[
   1,  2, 3, 4,  5,
   6,  7, 8, 9, 10,
  11, 12
]



Method 4: Using third-party library

The _.range() method is used to create an array of numbers progressing from the given start value up to, but not including the end value.

For installing `lodash`, run the following command

npm init -y
npm install lodash

Example:

Javascript




// Requiring the lodash library
const _ = require("lodash");
 
// Using the _.range() method
let range_arr = _.range(1,5);
 
// Printing the output
console.log(range_arr);


Output:

[ 1, 2, 3, 4 ]

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments