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

1
  • 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) Commented Jan 4, 2021 at 14:36

2 Answers 2

2

Try this

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

    return new Array(to - from + 1).fill('').map((v, i) => i + from);
}
Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.