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
  • 3,148
  • 1
  • 18
  • 32

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,521
  • 1
  • 17
  • 27
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
  • 19,346
  • 2
  • 17
  • 41
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
  • 37,143
  • 5
  • 39
  • 60
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
  • 376,160
  • 25
  • 347
  • 392