0

Does anybody have idea for easy clean way (maybe using ES6) to get

from "6" to array [1, 2, 3, 4, 5, 6] or "2" to [1, 2] etc.

I know I can use loop "for", but is there any shorter single-line way?

chojnicki
  • 2,674
  • 1
  • 12
  • 26

4 Answers4

2

You can use the spread operator on the created array [...Array(n).keys()]

console.log([...Array(6).keys()])
console.log([...Array(2).keys()])
// or
console.log(Array.from(Array(6).keys(), i => i+1));
console.log(Array.from(Array(2).keys(), i => i+1));
manikant gautam
  • 3,288
  • 1
  • 16
  • 26
2

Using Array.from() with mapFn

console.log(Array.from({length: 6}, (_, i) => i + 1));
console.log(Array.from({length: 2}, (_, i) => i + 1));
User863
  • 18,185
  • 2
  • 15
  • 38
2

You can use Array.from and it's callback

let range = num =>  Array.from({ length: num }, (_, i) => ++i)

console.log(range(6))
console.log(range(2))
console.log(range(-6))
Code Maniac
  • 35,187
  • 4
  • 31
  • 54
2

If you add the iterator, for example, to the prototype of Number, you could even spread numbers.

Number.prototype[Symbol.iterator] = function* () {
    for (var i = 0; i < this; i++) yield i;
};

console.log([...10]);
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358