1

How can I very simply convert an number into an array without doing a for loop?

Something like this:

var days = 30;
var days = days.toArray(); // Output - [1, 2, 3, 4, 5, 6, 7, 8, 9, ...]

What I currently do is following:

var days = 30;

var days = 30;
var array = [];

for(var i = 1;i <= 30;i++) {
  array.push(i);
}

console.log(array);
Mamun
  • 66,969
  • 9
  • 47
  • 59
Red
  • 6,599
  • 9
  • 43
  • 85
  • 2
    2.5K rep and no searching SO for something? https://stackoverflow.com/search?q=%5Bjavascript%5D+array+create+range+integers – mplungjan Sep 11 '18 at 17:00
  • 2
    Some people just ain't so good searching as others. I don't even know what the `range` method stand for. Now I do though. I was searching like so on SO and google: `convert number to array` and `convert number to array without loop`. – Red Sep 11 '18 at 17:02
  • no need to reinvent the wheel https://github.com/Gothdo/range – chiliNUT Sep 11 '18 at 17:05
  • OK I agree my google-fu is excellent :) – mplungjan Sep 11 '18 at 17:20

2 Answers2

3

Array.from()

Array.from() has an optional parameter mapFn, which allows you to execute a map function on each element of the array (or subclass object) that is being created. More clearly, Array.from(obj, mapFn, thisArg) has the same result as Array.from(obj).map(mapFn, thisArg), except that it does not create an intermediate array.

Try Array.from() by passing an object with length property as the first parameter and map function as the second parameter:

var days = 30;
var days = Array.from({length: days}, (v, i) => i+1);
console.log(days)
Mamun
  • 66,969
  • 9
  • 47
  • 59
1

You can use spread syntax.

Reference Document: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

array = [...Array(30).keys()]
console.log(array);
Ashu
  • 2,066
  • 3
  • 19
  • 33