Arrays are used to store multiple values in a single variable.
Each value is called an element, and each element has a numeric position in the array, known as its index.
Arrays are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on.
Arrays can contain any data type, including numbers, strings, and objects.
const arr1 = [2, 4, 6]; array
arr1[0]; element at index 0 → 2
arr1[1]; element at index 1 → 4
arr1[2]; element at index 2 → 6
arr1[3]; element at index 3 → undefined index not found
Numbers are used to represent both integer and floating-point values.
Numbers are most commonly expressed in literal forms like 255 or 3.14159 ↴
let num1 = 5; → number
let num2 = 2.5; → number
let num3 = num1 + num2;
console.log(num3); returns ↴
7.5 → number
Generate lottery numbers using ↴
Set Object → collection of unique values.
size() accessor property → returns the number of (unique) elements in the set.
has() method → returns true if a specified value exists in a Set, otherwise returns false.
add() method → insert a new element into a Set.
while loop → repeatedly executes a block of code as long as a specified condition is true.
Math.random() static method → returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1.
Math.floor() static method → always rounds down and returns the largest integer less than or equal to a given number.
Array.from() method → creates a new array instance from an array-like or iterable object.
sort() method → sorts the elements of an array in place and returns the reference to the same array, now sorted.
Set Object is a collection of unique values.
Each value can only occur once, each value is unique.
const mySet = new Set();
console.log(mySet); returns ↴
Set(0) {size: 0} → empty Set
To add values to the Set use the add() method.
mySet.add("a");
mySet.add("b");
mySet.add("c");
console.log(mySet); returns ↴
Set(3) {"a", "b", "c"} → values added
Try to add a duplicate value.
mySet.add("c"); character "c" is already in mySet
console.log(mySet); returns ↴
Set(3) {"a", "b", "c"} → no change
To find number of (unique) elements in the Set use the size accessor property.
console.log(mySet.size); returns ↴
3 → number of elements in the Set
while loop repeatedly executes a block of code as long as a specified condition evaluates to true.
while (condition) {
// execute code as long as condition is true
}
let x = 0; → counter
while (x < 4) {
console.log(x);
x++;
}
Initialize a counter variable x outside of the loop.
Condition x < 4 is checked before each iteration.
The loop will continue to run as long as x is less than 4
The loop repeatedly executes a block of code 4 times, from 0 to 3
For each iteration of the loop, the current value of x is printed to the console.
After each iteration, x is incremented by 1 x++
When x reaches 4 the condition evaluates to false, terminating the loop.
0
1
2
3 → printed to console
Math.random() static method returns a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive), with approximately uniform distribution over that range, which can be scaled to a desired range.
Math.random() always returns a number lower than 1
Math.random(); → 0.7409774889800926
Math.random(); → 0.5533596609238658
Math.random(); → 0.26768267226253617
returns random numbers between 0 (inclusive) and 1 (exclusive)
Math.floor() static method always rounds down and returns the largest integer less than or equal to a given number.
Math.floor(5.25); → 5
Math.floor(2.99); → 2
Math.floor(6.55); → 6
rounds down and returns the largest integer less than or equal to a given number.
Array.from() method returns an array from any object with a length property, such as Arrays, Strings, Sets, etc.
const mySet2 = new Set([2, 4, 6, 8, 4]);
console.log(mySet2); returns ↴
{2, 4, 6, 8} Set
Array.from(mySet2); returns ↴
[2, 4, 6, 8] → array
sort() method sorts the elements of an array as strings.
By default, the elements of the array are converted to strings and sorted in ascending order by comparing their sequences based on their UTF-16 code unit values.
sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.
sort() method is stable, it preserves the order of items in an array when their values are the same.
sort() method can sort an array of numbers, strings, or objects with custom functions.
syntax
array.sort()
By default the sort() method sorts the array in ascending order with the elements converted to strings.
This can lead to unexpected results when sorting arrays of numbers.
const arr2 = [2, 11, 1, 22, 33, 3];
arr2.sort(); returns ↴
[1, 11, 2, 22, 3, 33] NOT sorted accurately
To solve this limitation, a comparison callback function can be used to define the desired sorting order.
callback function a function passed into another function as an argument, which is then invoked within the outer function.
When sorting numbers,
For sorting an array of numbers in ascending order, the comparison function should subtract the second number from the first number.
syntax
array.sort(compareFunction)
comparison function
(a, b) => a - b compares two elements ↴
a and b
a - b calculates the difference between the two numeric values ↴
If the result is ↴
negative → a sorted before b
positive → a sorted after b
zero → order remains unchanged.
const arr3 = [2, 11, 1, 22, 33, 3];
arr3.sort((a, b) => a - b); returns ↴
[1, 2, 3, 11, 22, 33] → ascending order
The comparison function can be changed to sort in descending order by swapping the elements for comparison to b - a
const arr4 = [2, 11, 1, 22, 33, 3];
arr4.sort((a, b) => b - a); returns ↴
[33, 22, 11, 3, 2, 1] → descending order
Undefined and empty slots are moved to the end of the array.
const arr5 = [3, , undefined, 1, , 4, 2];
arr5.sort(); returns ↴
[1, 2, 3, 4, undefined, empty × 2]
Initialize a variable to hold the maximum number in the range.
const num1 = 59; → user input
Initialize a variable to hold the number of lottery numbers to generate.
const num2 = 6; → user input
Define a function genLotteryNumbers to generate lottery numbers.
function genLotteryNumbers(numsRange, count) {}
The function takes two numbers as input numsRange, count and returns a sorted array of numbers within the given range.
Minimum number in the range will always be 1
const min = 1 min
Create a Set to store unique numbers.
const nums = new Set() nums
Loop until the Set nums contains the desired number of unique numbers.
while (nums.size < count) {}
numsRange - min + 1 calculates the total number of possible values that can be generated.
Generate a random number within the specified range.
const randomNum =
Math.floor(Math.random() * (numsRange - min + 1)) + min randomNum
Add the random number to the Set nums
nums.add(randomNum)
Convert the Set nums to an array and sort it in ascending order before returning.
return Array.from(nums).sort((a, b) => a - b)
Call the function with ↴
genLotteryNumbers(num1, num2);
Generate lottery numbers.
const num1 = 59;
const num2 = 6;
function genLotteryNumbers(numsRange, count) {
const min = 1;
const nums = new Set();
while (nums.size < count) {
const randomNum = Math.floor(Math.random() * (numsRange - min + 1)) + min;
nums.add(randomNum);
}
return Array.from(nums).sort((a, b) => a - b);
}
call function
genLotteryNumbers(num1, num2);
returns ↴
[14, 23, 31, 50, 53, 54] → random numbers
Function returns a sorted array of 6 unique random numbers in the range of 1 to 59.