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 (N) and returns an array of numbers, from 1 to N:

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

#Arguments

  1. length defines the size of the array
  2. start defines the first number in the array (optional, defaults to 1)

#Example Usage

createArray(4); // [1, 2, 3, 4];
createArray(4, 0); // [0, 1, 2, 3];