0

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]
Reena Verma
  • 1,617
  • 2
  • 20
  • 47
  • See also: https://stackoverflow.com/questions/51529814/is-there-a-functional-way-to-init-an-array-in-javascript-es6 – Mark Nov 30 '19 at 21:52

3 Answers3

2

Use loop

const totalNumber = 3;
var arr = [];

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

console.log(arr);
blex
  • 24,941
  • 5
  • 39
  • 72
2

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))
0.sh
  • 2,659
  • 16
  • 37
1

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));
Ori Drori
  • 183,571
  • 29
  • 224
  • 209