# Arrays
- An array will be used to combine several related items into one variable
- These items kan we of anny kind like strings, numbers, objects, ...
- Similar to other variables, arrays don't need to be declared and can be initialized immediately e.g:
let students = [] - Use an index (between square brackets
[]and started from0) to read/overwrite an array element, as instudents[1] = 'John Doe'; - An array can be initialized at once by putting the element values (separated by commas) between square brackets
[], as inlet teachers = [ 'MichaΓ«l Cloots', 'Maartje Eyskens', 'Jan Janssen', 'Patrick Verhaert' ]; - You can loop over all elements of an array using a
forEach()structure - The property
lengthcan be used to get the number of elements in an array
REMARKS
- Unlike most other programming languages, JavaScript does not support associative arrays
- It's common practice to use a plural noun as array variable name (as an array usually contains multiple elements)
# Frequently used properties
| property | description |
|---|---|
length (opens new window) | the length of a array |
# Frequently used methodes
- Some array methodes with online examples:
| methode | description |
|---|---|
toString() (opens new window) | convert array to a comma separated sting |
concat() (opens new window) | joins two or more arrays |
push() (opens new window) | add a new element to the end of an array |
unshift() (opens new window) | add a new element at the beginning of an array |
shift() (opens new window) | remove the first element from an array |
pop() (opens new window) | remove the last element from an array |
splice() (opens new window) | remove, replace or add elements to an array |
slice() (opens new window) | returns a shallow copy of a portion of an array into a new array |
find() (opens new window) | returns the first found element in an array |
indexOf() (opens new window) | returns the index of the first found element in an array |
lastIndexOf() (opens new window) | returns the index of the last found element in an array |
findIndex() (opens new window) | returns the index of the first found element tha pass a test |
every() (opens new window) | returns true if every element in an array pass a test |
some() (opens new window) | returns true if one or more elements in an array includes a value |
includes() (opens new window) | returns true if one or more elements in an array pass a test |
fill() (opens new window) | fill one or more elements in an array with a static value |
from() (opens new window) | creates an array from an object literal |
reduce() (opens new window) | reduce the values of an array to a single value (going left-to-right) |
reduceRight() (opens new window) | reduce the values of an array to a single value (going right-to-left) |
- Some advanced but very useful methodes (aka higher-order functions) with extra examples:
| methode | description |
|---|---|
sort() (opens new window) | sort the order of the elements from lowest to highest |
reverse() (opens new window) | sort the order of the elements from highest to lowest |
map() (opens new window) | creates a new array populated with the transformed values inside the callback function |
filter() (opens new window) | creates a new array populated with the items that pass the test inside the callback function |
# Sorting arrays
- The
sort()method, without compare function, sorts an array alphabetically - Without comparing function, every element in the array is converted to a sting, and the sorted according to each character's UTF-16 code value (opens new window)
const a1 = 'A'; const a2 = 'a'; const zero = '0'; console.log(a1.charCodeAt(), a2.charCodeAt(), zero.charCodeAt()); // 65, 97, 48Copied!
1
2
3
4
2
3
4
- With a comparing function (parameters typical called
aandb) the sort order is:compareFunction(a, b)returns0, leaveaandbunchanged with respect to each othercompareFunction(a, b)returns a negative number, sortabeforebcompareFunction(a, b)returns a positive number, sortbbeforea
- Tip: this is also known as a three-way comparison (opens new window) function
# Array of strings (case-sensitive)
const names = ['John', 'bob', 'Ziggy', 'Adam', 'David']; console.log(names.sort()); // Adam, David, John, Ziggy, bob // Z (code 90) comes before b (code 98) console.log(names.reverse()); // bob, Ziggy, John, David, AdamCopied!
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# Array of strings (case-insensitive)
ascending order
descending order
const names = ['John', 'bob', 'Ziggy', 'Adam', 'David']; const namesSorted = names.sort((a, b) => { if (a.toLowerCase() < b.toLowerCase()) return -1; if (a.toLowerCase() > b.toLowerCase()) return 1; return 0; }); console.log(namesSorted); // Adam, bob, David, John, ZiggyCopied!
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# Array of numbers
- Because numbers are also converted to strings,
sort()without a compare function does not give the desired result
const numbers = [50, 1, 6.6, 8.3, 6, 30]; console.log(numbers.sort()); // 1, 30, 50, 6, 6.6, 8.3Copied!
1
2
3
4
2
3
4
- Inside the compare function numbers are not converted
ascending order
descending order
const numbers = [50, 1, 6.6, 8.3, 6, 30]; const numbersSorted = numbers.sort((a, b) => a - b); console.log(numbersSorted); // 1, 6, 6.6, 8.3, 30, 50Copied!
1
2
3
4
5
2
3
4
5
# Array of objects
score JavaScript ascending order
score PHP descending order
name ascending order
const scores = [ { name: 'John', JavaScript: 15, PHP: 12 }, { name: 'Adam', JavaScript: 10, PHP: 17 }, { name: 'David', JavaScript: 8, PHP: 6 }, { name: 'Ziggy', JavaScript: 14, PHP: 8 }, ]; const sortedScores = scores.sort((a, b) => a.JavaScript - b.JavaScript); console.log(sortedScores); /* { name: 'David', JavaScript: 8, PHP: 6 }, { name: 'Adam', JavaScript: 10, PHP: 17 }, { name: 'Ziggy', JavaScript: 14, PHP: 8 }, { name: 'John', JavaScript: 15, PHP: 12 }, */Copied!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Shuffle array
- You can use the three-way comparison to shuffles (randomly reorders) elements of the array
aandbcan be omitted inside the comparing function
yourArray.sort(() => 0.5 - Math.random());Copied!
1
# Copy (clone) array by value
- By default, arrays are copied by reference, not by value
- This means that when you set
array2 = array1both arrays point exactly to the same location in memory - When, for example, adding an element to
array1the new value is also available inarray2
const numbers1 = [4, 50, 12, 66]; const numbers2 = numbers1; numbers1.push(1000); console.log(numbers1); // 4, 50, 12, 66, 1000 console.log(numbers2); // 4, 50, 12, 66, 1000Copied!
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
- Use one of these methodes to clone an array (copy an array by value)
- old way:
const array2 = array1.slice() - ES6 way:
const array2 = [...array1](spread operator (opens new window))
- old way:
const hands1 = ['β', 'β', 'β']; const hands2 = [...hands1]; hands1.push('π€'); console.log(hands1); // 'β', 'β', 'β', 'π€' console.log(hands2); // 'β', 'β', 'β'Copied!
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# Transform with map()
- The
map()method creates a new array will take every returned value from the callback function and creates a new array using those values - The callback function passed to the
map()method accepts 3 arguments:element,index, and the array itself - Inside the callback function you can 'transform' every individual element (change a value, add extra key/values or remove a key/value)
- Open es6/arrays/map.html and es6/arrays/map.js
HTML
JavaScript
result
<div id="score"></div>Copied!
1
# Filter()
- The
filter()method creates a new array will take every value that pass the test inside the callback function - The callback function passed to the
filter()method accepts 3 arguments:element,index, and the array itself - Open es6/arrays/filter.html and es6/arrays/filter.js
HTML
JavaScript
result
<h4>Pass</h4> <div id="pass"></div> <h4>Fail</h4> <div id="fail"></div>Copied!
1
2
3
4
2
3
4
# Examples
# Bingo
- Bingo (opens new window) is a game of probability in which players mark off numbers between 1 and 75 on cards as the numbers are drawn randomly by a caller
- The winner being the first person to mark off all their numbers
- Open es6/arrays/bingo.html and es6/arrays/bingo.js
HTML
JavaScript
result
- Every click on
button#dropBall, picked a random number between1and75is picked from an array and append todiv#bingo
<!DOCTYPE html> <html lang="en"> <head> ... <style> #bingo div { display: inline-block; width: 50px; height: 50px; line-height: 50px; margin: 0.25rem; text-align: center; border: 10px solid #863637; background-color: wheat; box-shadow: inset 0 0 0.4em 0 rgba(0, 0, 0, 0.3); border-radius: 50%; font-size: 1.5rem; font-weight: bold; color: #863637; } </style> </head> <body> ... <p><button type="button" id="dropCoin" class="tertiary">drop next coin</button></p> <div id="bingo" class="border-gray"></div> ... </body> </html>Copied!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Change circle background
HTML
JavaScript
result
- In this example, we use the keyboard to change the color of
div#circle - You can find the code for every key on your keyboard on https://keycode.info/ (opens new window) (look at
event.code) - Open es6/arrays/circleBackground.html and es6/arrays/circleBackground.js
<!DOCTYPE html> <html lang="en"> <head> ... <style> #circle { width: 300px; height: 300px; line-height: 300px; font-size: 2rem; text-align: center; background-color: lightgray; border: 1px solid gray; border-radius: 50%; } </style> </head> <body> ... <div class="border-gray"> <p>Press a key (r, g, b, y, p or o) to change the color of this circle.</p> </div> <div id="circle">lightgray</div> ... </body> </html>Copied!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Higher order functions
# References
- Array class@Mozilla (opens new window)
- Array class@W3Schools (opens new window)



