# 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
length
can 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, 48
1
2
3
4
2
3
4
- With a comparing function (parameters typical called
a
andb
) the sort order is:compareFunction(a, b)
returns0
, leavea
andb
unchanged with respect to each othercompareFunction(a, b)
returns a negative number, sorta
beforeb
compareFunction(a, b)
returns a positive number, sortb
beforea
- 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, Adam
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# Array of strings (case-insensitive)
# 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.3
1
2
3
4
2
3
4
- Inside the compare function numbers are not converted
# Array of objects
# Shuffle array
- You can use the three-way comparison to shuffles (randomly reorders) elements of the array
a
andb
can be omitted inside the comparing function
yourArray.sort(() => 0.5 - Math.random());
1
# Copy (clone) array by value
- By default, arrays are copied by reference, not by value
- This means that when you set
array2 = array1
both arrays point exactly to the same location in memory - When, for example, adding an element to
array1
the 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, 1000
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);
// '✋', '✌', '✌'
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
# 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
# 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
# Change circle background
# Higher order functions
# References
- Array class@Mozilla (opens new window)
- Array class@W3Schools (opens new window)