1

I want to get a range number array and I write this function,

public static getNumberRange(from: number, to: number): number[] {

    return Array(to - from + 1).fill().map((v, i) => i + from);
  }

but I got a problem, because fill() needs a parameter.

any solution??

user1938143
  • 1,022
  • 2
  • 22
  • 46
  • 1
    You could just supply any parameter to `fill` - it's going to be ignored in the `.map` anyway. Or you can skip the two passes and do the operations at once with `Array.from({ length: to - from + 1 }, (v, i) => i + from)` – VLAZ Jan 04 '21 at 14:36

2 Answers2

2

Try this

public static getNumberRange(from: number, to: number): number[] {

    return new Array(to - from + 1).fill('').map((v, i) => i + from);
}
Waleed Nasir
  • 579
  • 5
  • 9
1

This is an annoying thing in JavaScript. If you create an array with X length (e.g. new Array(5)) you will get [empty × 5] array. Even if this array has 5 length, you can't map it.

And here comes array.fill function. In your case you don't care about the value, so you can just fill with undefined values:

Array(to - from + 1).fill(undefined).map((v, i) => i + from)

And after filling with undefined values, only then you can map it.


Also for your case you can find a lot of alternative solutions: Does JavaScript have a method like “range()” to generate a range within the supplied bounds?

KiraLT
  • 2,385
  • 1
  • 24
  • 36