Categories

# How to Generating a Number Array within a Range with JavaScript?

To generate a number from a minimum to a maximum number, we can do it in a few ways. If we want each entry to increment by 1, we can use the `Array.from` method. The `Array.from` method takes an object which has the `length` property.

To generate a number within a range, like from 1 to 10, we can make a constant for the maximum number and another one for the minimum number. Then the length would be the maximum minus the minimum plus one.

We need to add one since the maximum minus the minimum is one less than the length we want. The second argument of the `Array.from` method is a function that lets us map the values to the ones we want.

The first parameter is the value of the original array since we didn’t pass in an array into the first argument, this parameter isn’t useful for us.

The second argument is the index of the array, which will range from 0 to the length which we specified as the `length` property minus 1. So if we want to generate an array of numbers from 1 to 10, we can write:

``````const max = 10;
const min = 1;
const arr = Array.from({
length: max - min + 1
}, (v, i) => min + i);
console.log(arr)
``````

In the code above, we specified the `length` property of the array that we’ll generate, which is `max — min + 1` or 10 – 1+1, which is 10. That’s the length we want. In the second argument, we have a function that maps the index `i` into `min + i`, which is will be `1 + 0` , `1 + 1` , `1 + 2` , …, up to `1 + 9` . Then if we run the `console.log` statement in the last line of the code above, we get:

``````[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
``````

It’s easy to generate different kinds of number arrays by adjusting the function in the second parameter since it maps to any number we want. To generate the first `n` odd numbers, we can write:

``````const arr = Array.from({
length: 10
}, (v, i) => 2 * i + 1);
console.log(arr)
``````

In the code above, we have a function that generates odd numbers from a formula. `2 * i + 1` always generates an odd number since 2 times any integer is an event number, so if we add 1 to it, then it will become an odd number. It’s useful for any number sequence that has a pattern that can be put into a formula or be expressed in terms of conditionals or other flow control statements.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.