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?

2
  • Can you post the code you've tried ? Commented Apr 5, 2020 at 12:07
  • 1
    btw, index starts with zero. Commented Apr 5, 2020 at 12:07

4 Answers 4

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

2
  • you can also apply a mapping function to get the same output as OP: Array.from(Array(6).keys(), i => i+1) Commented Apr 5, 2020 at 12:09
  • 1
    @NickParsons agreed Commented Apr 5, 2020 at 12:13
2

Using Array.from() with mapFn

console.log(Array.from({length: 6}, (_, i) => i + 1));
console.log(Array.from({length: 2}, (_, i) => i + 1));

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

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.