2

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?

Michael Embassy
  • 89
  • 4
  • 10

2 Answers2

4

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)));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

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;
}
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44