Constructing Arrays

• Array of given length:
Array(length)
or new Array(length)
• Array with at least two given elements:
[element1, element2, ...]
Array(element1, element2, ...)
new Array(element1, element2, ...)
• Array.of(element1, ...) works with single integer element
• Array.from(iterable) like [...iterable]
• Array.from(iterable, mapFun, thisArg) transforms the source elements:
Array.from('Hello', x => x.toUpperCase())
→ [ 'H', 'E', 'L', 'L', 'O' ]


Array Mutators

• x = arr.pop(), arr.push(x): Removes, adds last element.
• x = arr.shift(), arr.unshift(x): Removes, adds first element.
• deleted = arr.splice(start, deleteCount, x1, x2, ...)
• If deleteCount > 0, elements are deleted at start
• If x1, x2, ... are present, they are inserted at start
• If deleteCount is absent, all element from start on are deleted.
• arr.copyWithin(target, start, end)
• If target, start, end < 0, they are counted from the end.
• start defaults to 0, end to arr.length.
const arr = [0, 1, 4, 9, 16, 25]
arr.copyWithin(0, 1) // arr is now [1, 4, 9, 16, 25, 25]
arr.copyWithin(1) // arr is now [1, 1, 4, 9, 16, 25]

• Note: By writing to the length property, you can resize the array.

Array Mutators

• arr.fill(value, start, end)
• start defaults to 0, end to arr.length.
• arr.reverse() reverses arr in place and returns arr
• arr.sort(compareFunction) sorts arr in place and returns arr
const arr = [0, 1, 16, 25, 4, 9]
arr.sort((x, y) => x - y) // arr is now [0, 1, 4, 9, 16, 25]

• The comparison function compares two elements x, y and returns
• a negative number if x should come before y
• a positive number if x should come after y
• 0 if they are indistiguishable
• Caution: If the compare function is not provided, elements are converted to strings and lexicographically compared by UTF-16 code units.
const arr = [0, 1, 4, 9, 16, 25]
arr.sort() // arr is now [0, 1, 16, 25, 4, 9]

Array Accessor Methods

• arr.includes(target, fromIndex), arr.indexOf(target, fromIndex), arr.lastIndexOf(target, fromIndex) searches for target
• fromIndex defaults to 0
• If fromIndex < 0, counts from the end of the array.
• arr.slice(begin, end) yields a shallow copy of the given range.
• begin defaults to 0, end to arr.length
• arr.slice() is the same as [...arr]
• arr.concat(value1, value2, ...) yields an array starting with arr, to which the values are concatenated.
• Array values are spread, everything else is appended
[1, 2, 3].concat(4, {age: 5}, [6, 7]) → [ 1, 2, 3, 4, { age: 5 }, 6, 7 ]
• arr.join(separator) yields a string joining all elements, using the given separator
• The default separator is ','
[1,2,3,[4,5]].join(' and ') → '1 and 2 and 3 and 4,5'

Array Accessors

• (ES2019) arr.flat(levels) flattens multidimensional arrays. The default is to flatten one level.
[[1, 2], [3, 4]].flat() → [1, 2, 3, 4]

• arr.keys(), arr.values(), arr.entries() yield iterables to the index values, elements, and [index, element] pairs.
const arr = [0, 1, 4, 9]
[...arr.entries()] → [[0, 0], [1, 1], [2, 4], [3, 9]]


Iteration Methods

• arr.forEach(f) calls f(element, index, arr) for each element.
• All methods on this slide have an optional thisArg argument that sets this in f
• arr.map(f) yields an array of all values returned from f(element, index, arr)
• (ES2019) arr.flatMap(f) flattens the values returned from f(element, index, arr) and yields their concatenation.
• arr.filter(f) yields an array of all values for which f(element, index, arr) is true
• arr.every(f), arr.some(f) yields true if f(element, index, arr) is true for every or at least one element.
• arr.find(f), arr.findIndex(f) finds the first element, or its index, for which f(element, index, arr) is true

Reduction

• a.reduce(f) computes a value from the elements of a, using f to combine them as f(...f(f(a[0], a[1]), a[2])...,a[n-1])
[1, 2, 3, 4].reduce((x, y) => x + y) → 10 // ((1 + 2) + 3) + 4
[1, 2, 3, 4].reduce((x, y) => 10 * x + y) → 1234
[1, 9, 7, 2].reduce((x, y) => Math.max(x, y)) → 9

• a.reduce(f, init) computes f(...f(f(init, a[0]), a[1])...,a[n-1])
[1, 2, 3, 4].reduce((x, y) => x - y, 0) → -10 // (((0 - 1) - 2) - 3) - 4

• reduceRight associates from the right in reverse order: f(f(...f(a[n - 1], a[n - 2])..., a[1]),a[0])
[1, 2, 3, 4].reduceRight((x, y) => [x, y]) → [[[4, 3], 2], 1]


Typed Arrays

• Typed arrays efficiently store sequences of fixed-size numbers:
Int8Array
Uint8Array
Uint8ClampedArray
Int16Array
Uint16Array
Int32Array
Uint32Array
Float32Array
Float64Array
• Fixed element type, no holes
• Uint: unsigned integer
• Clamped:
• Setting an out-of-range value sets 0 or 255, non-integer sets nearest integer
• Produced by HTML Canvas getImageData
• Negative index values count from the end of the array!

canvasdata.html

Array Buffers

• Data from a file, data stream, image, etc. stored in array buffer.
• Supported by File API, XMLHttpRequest, WebSockets, ...
• If the data is an array, construct a typed array to process the buffer contents:
const buffer = ...
const arr = new Uint16Array(buffer)

• If the data has a different structure, use a DataView instead:
const view = new DataView(buffer)

• Read with DataView methods getInt8, getInt16, getInt32, getUInt8, getUInt16, getUInt32, getFloat32, getFloat64:
let value = view.getUint32(offset, true)

• Last parameter is true for little-endian byte order, false (the default) for big-endian.
• Write with set method:
view.setUint32(offset, newValue, true)

• Note: Typed arrays always use the endianness of the host platform.

Maps

• A map is an unordered sequence of key/value pairs.
• Unlike objects, keys can be of any type, not just String/Symbol.
• Unlike objects, no prototypes.
• Remembers insertion order.
• A map is an iterable that yields [key, value] pairs.
• Can be used in loop
for (const [key, value] of map)
• Key equality: === except that all NaN are equal.
• Implemented as hash table.
• Key hash function derived from primitive type value or object reference.
• Equality, hash function cannot be changed.
• Typical application: Associate property with DOM nodes without adding properties directly into the nodes.

Map Operations

• new Map() makes empty map.
• new Map(iterable), where iterable produces an array of pairs [key, value]
• size property
• Another reason not to use objects for maps.
• map.set(key, value) adds the key/value pair, returns map
• map.delete(key) removes key and its associated value and returns true if the key was present, returns false otherwise.
• map.has(key), map.get(key) return true/the associated value if the key is present, false/undefined otherwise.
• map.clear() empties the map.
• map.forEach(f, thisArg) invokes f(key, value) on each element.
• keys, values, entries yield iterators over the keys, values, and [key, value] pairs.

Sets

• Collects elements without duplicates.
• Remembers insertion order.
• Equality: === except that all NaN equal another.
• Sets are iterable, producing their elements.
for (const element of set) ...

• Construct as new Set() or new Set(iterable), where iterable produces elements.
• Typical use: Collect DOM nodes that fulfill a Boolean property.

Set Operations

• size property yields number of elements.
• set.add(x) adds x if not present and returns set
• set.delete(x) deletes x and returns true if x was present, returns false otherwise.
• set.has(x) tests whether x is present.
• set.clear() deletes all elements.
• set.forEach(f, thisArg) invokes f(element, element) on each element.
• keys, values, entries yield iterators over elements, elements, and pairs [element, element]

Weak Maps and Sets

• Map keys/set elements are “weak references”.
• If there are no other references, the key and associated value/set element are removed.
• The keys/elements must be objects, not primitive type values.
• Good for DOM elements as keys/elements.
• No traversal methods.
• Weak maps/sets are not iterable.
• The only WeakMap methods are set/delete/get/has
• The only WeakSet methods are add/delete/has