Fill up an array with integer by using a range

Fill up an array with integers by using a range

When working with TypeScript, you may often come across the need to create an array of integers that follow a specific range. This can be useful in various scenarios, such as generating a sequence of numbers for calculations or populating a dropdown menu with options. In this blog post, we will explore different approaches to fill up an array with integers by using a range.

1. Using a for loop

One straightforward way to fill up an array with integers is by using a for loop. By iterating over the desired range, we can push each integer into the array.

const rangeArray: number[] = [];

for (let i = start; i <= end; i++) {
  rangeArray.push(i);
}

console.log(rangeArray);

In the above code snippet, replace start and end with the desired range values. The loop will iterate from the start value to the end value, pushing each integer into the rangeArray. Finally, we log the array to the console to verify the output.

2. Using Array.from() method

An alternative approach is to use the Array.from() method, which creates a new array from an iterable object. We can pass a range object to this method and specify a mapping function to generate the desired sequence of integers.

const rangeArray = Array.from({ length: end - start + 1 }, (_, index) => index + start);

console.log(rangeArray);

In the above code snippet, end - start + 1 determines the length of the array. The mapping function (_, index) => index + start generates each integer in the range by adding the current index to the start value. Finally, we log the array to the console.

3. Using Array.fill() and Array.map() methods

Another approach involves using the Array.fill() method to create an array of a specific length filled with a placeholder value. We can then use the Array.map() method to replace each placeholder value with the desired integers.

const rangeArray = new Array(end - start + 1).fill(0).map((_, index) => index + start);

console.log(rangeArray);

In the above code snippet, new Array(end - start + 1).fill(0) creates an array of the desired length filled with zeros. The mapping function (_, index) => index + start replaces each zero with the corresponding integer in the range. Finally, we log the array to the console.

Now that you have learned different approaches to fill up an array with integers by using a range, you can choose the one that best suits your needs. Whether you prefer a traditional for loop, the convenience of Array.from(), or the combination of Array.fill() and Array.map(), these methods will help you generate the desired sequence of numbers efficiently.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *