Creating an Array from 1 to N

Toggle Light/Dark Mode

Posted on

I'm generally good about memorizing common concepts (Array.reduce() comes to mind)... but despite using it quite often, this is one that I've had a hard time committing to memory.

Here is TypeScript function which takes a number and returns an array of numbers, from 1 to N:

const createArray = (n: number): number[] => {
  return Array.from({ length: n }, (_, i) => i + 1);
};