3

I want to create a function that takes input from user and returns an array with all the numbers from 1 to the passed number as an argument. Example: createArray(10) should return [1,2,3,4,5,6,7,8,9,10]. I came up with this solution:

function createArray(input) { var value = 0; var array = []; for (i=0;i<input;i++) { value++; array.push(value) console.log(array) } } createArray(12); 

What is the correct and better way of doing it?

0

2 Answers 2

5

I would prefer to use Array.from:

const createArray = length => Array.from( { length }, // Mapper function: i is the current index in the length being iterated over: (_, i) => i + 1 ) console.log(JSON.stringify(createArray(10))); console.log(JSON.stringify(createArray(5)));

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

Comments

2

There is no need for the extra variable just do this:

function createArray(input) { var array = []; for (i = 0; i <= input; i++) { array.push(i); } return array; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.