-3

i have a number 10 how to convert to this to number array in java script. answer should be [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

OR How to convert number(10) to number of items in array in javascript

Santhosh
  • 1,053
  • 1
  • 20
  • 45
  • Posible duplicated: [How to initialize an array's length in javascript?](https://stackoverflow.com/questions/4852017/how-to-initialize-an-arrays-length-in-javascript) – Yosvel Quintero Jan 28 '19 at 10:35
  • 1
    One problem with marking duplicates, the marked duplicate was asked back in 2010,. Things have moved on, and a nice feature of filling arrays these days would be with an iterator. The marked duplicate has this, but it's buried deep within all the other answers, one had 7 up-votes & the other had 1, until I up-voted them. Might take a while before those get near the top :) Doing something like `Array.from(numRange(1, 10))` in the long run just looks nice.. – Keith Jan 28 '19 at 10:54

2 Answers2

3

A simple for loop will easily accomplish this task.

var number = 10;
var arr = [];

for(var i = 0; i < number; i++) arr.push(i+1);

console.log(arr)

You can also use:

Array.from(new Array(number), (x,i) => i+1)

var number = 10;

var arr = Array.from(new Array(number), (x,i) => i+1)

console.log(arr)
Adrian
  • 8,271
  • 2
  • 26
  • 43
  • 1
    Might be the same people who marked as duplicate. Technically it's a duplicate, but from 2010, it might have still be a good idea to keep this one open so that modern ways of doing this can be shown. Especially using generators, as that's really hidden inside the dupe. ps. I'll up-vote, as your correct is wrong when they do this. – Keith Jan 28 '19 at 11:01
0

Lets say you have a variable let a which implies your last number in array and at the same time number of elements in array.

let a = 10;

Now initialize an array which you will populate with numbers

let arr = [];

Now do a for loop and push the numbers in the array.

for (let i = 0; i < a; i++)
    arr.push(i+1);

This will populate array arr with numbers from 1 to 10.

Mirakurun
  • 4,859
  • 5
  • 16
  • 32