Reena Verma
Reena Verma

Reputation: 1685

Create an array from 1 number, (which increments)?

How do I create an array, which increments up to a certain number?

For example, I have a variable, with the value of 3:

const totalNumber = 3;

Is it possible, to convert this to an array, but the array increments from every number, up to and including 3?

For example, I would want the out put to be:

[1,2,3]

So if the value was 10, output would be:

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

Upvotes: 0

Views: 923

Answers (3)

Ori Drori
Ori Drori

Reputation: 193348

You can use Array.from() and pass the number as the length of the array:

const getArr = length => Array.from({ length }, (_, i) => i + 1);

console.log(getArr(3));
console.log(getArr(10));

This is actually a private case of the range function:

const range = (start, stop, step = 1) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));

console.log(range(1, 3));
console.log(range(1, 10));

Upvotes: 1

0.sh
0.sh

Reputation: 2752

you can use a simple for..loop to hanlde this


function arrayFromArg(totalNumber) {
    let newArray = [];
    for ( let i = 1 ; i <= totalNumber ; i++ ) {
        newArray.push(i)
    }
    return newArray;
}

console.log(arrayFromArg(3))
console.log(arrayFromArg(10))

Upvotes: 2

Kaloyan Velichkov
Kaloyan Velichkov

Reputation: 197

Use loop

const totalNumber = 3;
var arr = [];

for(var i=1; i<=totalNumber; i++) {
    arr.push(i);
}

console.log(arr);

Upvotes: 2

Related Questions