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);

4
  • 2
    2.5K rep and no searching SO for something? stackoverflow.com/… Commented Sep 11, 2018 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. Commented Sep 11, 2018 at 17:02
  • no need to reinvent the wheel github.com/Gothdo/range Commented Sep 11, 2018 at 17:05
  • OK I agree my google-fu is excellent :) Commented Sep 11, 2018 at 17:20

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

4 Comments

This did it for me (taken from the duplicate) var array = [...Array(30]
suggestion: i+1, to let your answer exactly the same as asker desired result :D
Nvm, I take your anwser as this is supported in IE aswell, thanks! :)
@Red, you are most welcome :)
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);

1 Comment

Starts at 0 not 1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.