Subscribe to my email list now at http://jauyeung.net/subscribe/
Follow me on Twitter at https://twitter.com/AuMayeung
Many more articles at https://medium.com/@hohanga
Even more articles at http://thewebdev.info/
JavaScript, like any other programming language, has many handy tricks that let us write our programs more easily. In this article, we will look at how to do different things that involve numbers, like generating a number array, generating random numbers, and shuffling numbers.
Generating a Number Array within a Range
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.
Generate Random Numbers
The JavaScript standard library has a Math
object, which has a random
method to generate random numbers between 0 and 1. It takes no arguments.
By itself, it’s of limited use since it can only generate numbers between 0 and 1, but we can easily use it to generate random numbers in any range.
For example, if we want to generate a number between a minimum and a maximum number, we can write the following code:
const min = 1;
const max = 100;
const num = Math.random() * (max - min) + min;
console.log(num);
In the code above, we have a formula that has the min
number as the minimum number, then we add Math.random() * (max — min)
to min
. max-min
would be positive since max
is bigger than min
and Math.random()
returns a number between 0 and 1 so it would either be 0 or positive.
If max
is the same as min
, then we get min
as the result of num
, which is the lowest number we’ll accept, and if Math.random()
is 0 we get the same thing.
If Math.random()
is 1, we get max — min + min
which is the same as max
. This means that the formula would never be outside of the number range between min
and max
, which is what we want. The formula above will get us any floating-point number. If want integer results only, we can write:
let min = 1;
let max = 10;
min = Math.ceil(min);
max = Math.floor(max);
const num = Math.floor(Math.random() * (max - min)) + min;
console.log(num);
In the code above, we rounded down our result to the nearest integer with the Math.floor(Math.random() * (max — min))
method call. This makes sure the result generated would be between 1 inclusive and 10 exclusive.
Generate an Array of Random Numbers
We can easily expand the code above to generate an array of random numbers. Using the Array.from
method that we used above, we can create the array like in the following code:
const arr = Array.from({
length: 10
}, (v, i) => {
const min = 1;
const max = 10;
return Math.random() * (max - min) + min
});
console.log(arr)
In the second argument of the Array.from
method call, we modified the function for mapping the values to the number generator function with the code inside it as the same code that we used to generate random numbers.
Again, we can specify the length
property of the object in the first argument to the length of the array that we want. If we run the code above, the console.log
output from the statement on the last line should log something like:
[2.09822597784169, 9.485219511793478, 4.905513590655689, 5.428402066955793, 5.874266428138649, 6.288415362686418, 2.768483595321933, 9.849179787675595, 1.1291148797430082, 6.725810669834928]
Also, we can use the integer generator code that we have before in the same manner, like in the code below:
const arr = Array.from({
length: 10
}, (v, i) => {
let min = 1;
let max = 10;
min = Math.ceil(min);
max = Math.floor(max);
return num = Math.floor(Math.random() * (max - min)) + min;
});
console.log(arr)
We have the same code that we used to generate integers as before, except that we used it to generate an array of random integers. If we run the code above, we should get something like the following:
\[8, 3, 5, 4, 4, 9, 9, 1, 1, 1\]
from the console.log
statement above.
Shuffling an Array of Numbers
With the sort
method built into the JavaScript array objects, we can use it easily to sort arrays. The sort
method takes a function that lets us compare 2 entries in the array to let us set the sort order between 2 elements based on the conditions that we specify.
The function that we pass into the sort
method takes 2 parameters, the first is an element which we call a
, and the second is an element which we call b
, and we compare a
and b
to determine which should be sorted above the other in the array. The sort function expects a number to be returned by the callback.
If the value that’s returned by our function is negative, then a
will be in an array index that’s lower than b
. That is, a
comes before b
. If the number is positive, then b
will come before a
. If the function returns 0, then a
and b
will stay in their original position.
If we want to shuffle the array, we can just return a random number from it — the value of a
or b
will not have an impact on the sort. We can once again use the Math.random()
method to help us generate a random return value for the function we pass into the sort
method. We can write the following code to sort each entry in random order (shuffle the array):
let nums = [49, -151, 88, -133, -164, 78, 117, -25, 76, -40];
nums = nums.sort(() => {
return Math.random() - 0.5
});
console.log(nums);
In the code above, our sort
method has a function which generates a random number between -0.5
and 0.5
, which means there’s a chance that each element either stays in place or gets shuffled, according to what the sort
method will do depending on the return value.
The Math.random()
only returns numbers between 0 and 1. However, we can easily make it more useful by extending it in the ways that we did above. We can specify a range between a minimum and a maximum number and Math.random() * (max — min) + min
to generate a number between a range. Also, we can pass it into the callback function of the sort
method by returning Math.random() — 0.5
to generate a number between -0.5
and 0.5
, which means that it can be shuffled (or not) depending on the sign of the generated number and whether it’s 0 or not.