Arrays Flashcards

1
Q

Array.from()

A

Array Static Method

Array.from(arrayLike[, mapFn[, thisArg]])

Parameters

  • arrayLike - an array-like or iterable object to convert to an arrary. ex. arguments, document.getQuerySelectorAll()
  • mapFn - map function to call on every element - results will be applied to the new array.
  • thisArg - value to use as this when executing mapFn

Return

A new array instance

Notes

  • Lets you create Arrays from:
    • array-like objects
      • those with a length property and indexed elements like arguments or NodeList
    • iterable objects
      • objects that have implemented the @@iterator method, like Map, Set, String, Array
  • This is the official replacement for [].slice.call(arrLike)
  • Array.from(obj, mapFn, thisArg) has same result as Array.from(obj).map(mapFn, thisArg) except that it doesn’t create an intermediate array.
    • Not creating an intermediate array is useful if you were doing Uint8Array.from( on values that would be truncated, unless you used the former version which maps the values before creating the new Uint8Array
  • Converts holes to value undefinedU
  • Should only use on array-like objects to create new array from it (with possible mapFn).
    • For creating new array from iterable objects, use spread syntax instead ...arr

<small>Research HTMLCollection, FileList, NodeList - all these elements that are array-like</small>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Array.isArray()

A

Array Static Method

Array.isArray(obj)

Parameters

  • obj - the object to be checked

Return

  • true if array; otherwise false

Notes

  • Always use Array.isArray() rather than instanceof because instanceof does not work through iframes
  • Always returns false for instances of TypedArray
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Array.of()

A

Array Static Method

Array.of(element0[, element1[, ...[, elementN]]])

Parameters

  • elementN - elements with which to create the new array

Return

  • A new array instance

Notes

  • Array.of(3) will create a new Array with one element of which it’s value is 3. [3]
  • Array(3) will create an empty Array of length 3.
  • Polyfill is simply: Array.prototype.slice.call(arguments)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Array.prototype.copyWithin()

A

Array Instance Mutator Method

arr.copyWithin(target[, start[, end]])

Shallow copies part of an array to another location in the same array and returns it, without modifying size. If need be, copied section will be trimmed to fit arr.length

Parameters

  • target - 0-based index at which to copy the sequence to. If negative, counted from end. If at or greater than arr.length, nothing will be copied.
  • start - 0-based index at which to start copying element from. If negative, counted from end. If omitted, will start from the beginning (0) by default.
  • end - 0-based index at which to end copying elements from. Copies up to but not including end element. If negative, counted from end. If omitted, will copy to the end (default to arr.length)

Returns

  • The modified array

Notes

  • Intentionally generic, does not need to be Array object operating on.
  • If any parameters are negative, can be seen as length+parameter (ie. length+start)

Research

  • Works like to memmove from C/C++, high performant

The sequence is copied and pasted as one operation; pasted sequence will have the copied values even when the copy and paste region overlap.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Array.prototype.fill()

A

Array Instance Mutator Method

arr.fill(value[, start[, end]])

Fills all elements of an array from a start index to end index with a static value.

Parameters

  • value - value to fill in array
  • start - start index, defaults to 0
  • end - end index, which is not included and defaults to this.length

Returns

  • The modified array

Notes

  • Intentionally generic, does not need to be Array object operating on.
  • When gets passed an object, it will copy the reference to the object and fill the array with references
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Array.prototype.pop()

A

Array Instance Mutator Method

arr.pop()

Removes the last element from an array and returns that element. This method changes the length of the array.

Returns

  • The removed element from the array.
  • undefined if array is empty
    • be careful for a value in the array being undefined and returned, thus assuming that the array is now empty
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Array.prototype.push()

A

Array Instance Mutator Method

arr.push([element1 [, ...[, elementN]]])

Adds one or more elements to the end of the array and returns the new length

Returns

  • The new length of the modified array

Notes

  • Since apply takes arguments as an array, we can merge two arrays as if we were using concat()Array.prototype.push.apply(arr1, arr2)
    • Must be careful. We easily run the risk of going over the limit of apply()since there’s a max number of parameters one function can handle
  • Is very generic. Can be used on objects as well.
    • Would increment (or create) the length property and add an indexed property on the object
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Array.prototype.reverse()

A

Array Instance Mutator Method

arr.reverse()

Reverses an array in place

Returns

  • The reversed array.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Array.prototype.shift()

A

Array Instance Mutator Method

arr.shift()

Removes the first element from the array and returns it. Modifies the length of the array.

Returns

  • The removed element from the array.
  • undefined if the array is empty.
    • again, note that a value could be undefined, returned undefined doesn’t necessarily mean empty array

Notes

  • Removes element at 0-th index and consecutively shifts indexes down throughout the rest of the array.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Array.prototype.sort()

A

Array Instance Mutator Method

arr.sort([compareFunction])

Sorts the array in place and returns the array. Sort is not necessarily stable. Default sort order is by Unicode code points

Parameters

  • compareFunction - function that defines the sort order. If omitted, sort is done according to Unicode code points, converting elements to strings if necessary.

Returns

  • The sorted array, in place

Notes

  • Since it’s not stable, two equal items may be in a different order than they were inserted into the array.
  • All undefined elements and ‘holes’ are sorted to the end of the array, (undefined before ‘holes’)
  • In unicode code points - 80 comes before 9 because values are converted to strings. Must use compareFunction for numbers
    • return a < b ? -1 : (a > b ? 1 : 0);
      • use this over a - b since that can cause numeric overflow
  • If compareFunction(a,b) returns less than 0, sort a at a lower index than b
  • If compareFunction(a,b) returns 0, the elements are equal
  • If compareFunction(a,b) is more than 0, sort a at a lower index than b
  • return a.localeCompare(b) for strings that have non-ASCII characters but still should be sorted properly.
  • If have high overhead with sorting on nested objects, or complex arrays, use map to extract actual values into { index: i, value: el.name.toLowerCase().reverse() }, sort() the mapped object, then construct array again within another map using return originalArray[el.index]
    • because the compareFunction could be called multiple times on the same element when sorting an array, thus best to only have it done once on each element, as in a map

Study numeric overflow

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Array.prototype.splice()

A

Array Instance Mutator Method

arr.splice(start[, deleteCount[, item1[, item2[, ...]]]])

Changes contents of an array by removing existing elements or adding new ones, starting at a defined index.

Parameters

  • start - Index at which to start changing the array
  • deleteCount - the number of old array elements to remove. If number is greater than those left in array, or if parameter omitted, then all from startto end of array will be deleted
  • item1, item2, ... - Elements to add to the array starting at the start index

Return

  • Array containing the deleted elements.
  • If one element removed, then array of one is returned
  • If no elements removed, then empty array returned

Notes

  • Possible for length of array to change if inserting more than you are deleting
  • If deleteCount is 0 or negative, no elements are removed
  • If start is NaN, will be treated as 0
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Array.prototype.unshift()

A

Array Instance Mutator Method

arr.unshift(element1[, ...[, elementN]])

Adds one or more items to the beginning of the array and returns the new length.

Parameters

  • elementN - items to add to the front of the array

Return

  • The new length property of the object upon which this method was called

Notes

  • Made intentionally generic. Can be called or applied on objects resembling arrays.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Array.prototype.concat()

A

Array Instance Accessor Method

const new_array = old_array.concat(value1[, ...[, valueN]])

Merge two or more arrays, and returns a new array with original unchanged. Can also merge in values, not just arrays.

Parameters

  • value - Arrays and/or values to concatenate into a new array.

Return

  • A new Array instance

Notes

  • Copies, in order, the values from the array argument into the new array, by making shallow copies. Any object references will be kept.
  • If an argument is not an array but a value, it will be copies in the proper order as the next item in the new array
  • It does not recurse into nested array arguments
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Array.prototype.includes()

A

Array Instance Accessor Method

arr.includes(searchElement[, fromIndex])

Determines whether an array includes a certain element, returning true or false as appropriate.

Parameters

  • searchElement - The element to search for
  • fromIndex - The position in the array at which to begin searching for searchElement. If negative, searches from that absolute value before arr.length

Return

  • A Boolean

Notes

  • If fromIndex is >= length of array, then false is returned.
  • If fromIndex is less than 0, then the entire array is searched.
  • includes() is intentionally generic and doesn’t need to be used on an Array object.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Array.prototype.indexOf()

A

Array Instance Accessor Method

arr.indexOf(searchElement[, fromIndex])

Returns the index at which the given searchElement is first found, otherwise returning -1 if not found.

Parameters

  • searchElement - The element to locate in the array.
  • fromIndex - Index at which to start searching from. If offset is calculated to be 0 or less, whole array is still searched. Defaults to 0.

Return

  • The first index of the element in the array, -1 if not found.

Notes

  • Uses === strict equality to compare.

Research ways to find all occurences of an element in an array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Array.prototype.join()

A

Array Instance Accessor Method

arr.join([separator])

Joins all element of an array (or array-like) object into a string.

Parameters

  • separator - A string to separate each pair of adjacent elements of the array. It is converted to a string if necessary, and if omitted, elements are separated with a comma ,. If it’s an empty string, elements are joined without any spaces between them.

Return

  • A string with all array elements joined. If arr.length is 0, empty string is returned.

Notes

  • If an element in the array is undefined or null, it’s converted to an empty string.
17
Q

Array.prototype.lastIndexOf()

A

Array Instance Accessor Method

arr.lastIndexOf(searchElement[, fromIndex])

Returns the last index at which a given element is found in the array, by searching the array backwards. Returning -1 if not present.

Parameters

  • searchElement - Element to locate in the array.
  • fromIndex - Index at which to start searching backwards. Even if it is negative, array is still searched backwards from that index.

Return

  • Last index at which element is found, -1 if not present.

Notes

  • Compared using strict equality ===
18
Q

Array.prototype.slice()

A

Array Instance Accessor Method

arr.slice([begin[, end]])

Returns a shallow copy of a defined portion of the array, from begin to end (end element not included). Original array not modified.

Parameters

  • begin - 0-based index at which to begin extraction. Defaults to 0.
  • end - Extracts up to, but not including, this index. Defaults to arr.length.

Return

  • A new array containing the extracted elements.

Notes

  • Commonly used to convert array-like objects to actual arrays.

Research

`var unboundSlice = Array.prototype.slice;`
`var slice = Function.prototype.call.bind(unboundSlice)`
`var theList = slice([array-like-object])`
19
Q

Array.prototype.toString()

A

Array Instance Accessor Method

arr.toString()

Overriding Object.prototype.toString(), it joins the elements of an array with commas and returns a string, representing the array.

Return

  • A string representation of the array.

Notes

  • Used when a text value is needed or when an array is referred to in string concatenation.
20
Q

Array.prototype.toLocaleString()

A

Array Instance Accessor Method

arr.toLocaleString()

Returns a string representing the array by calling toLocaleString() on each element of the array.

Parameters

  • locales - A string with a BCP 47 language tag, or array of such strings.
  • options - An object with configuration properties.

Return

  • A string representing the elements of the array.

Research getting it working, not needing to be on a machine of that locale, just with the options.

21
Q

Array.prototype.entries()

A

Array Instance Iteration Method

arr.entries()

Returns a new Array Iterator object that contains key/value pairs for each index of the array.

Return

  • An Array Iterator object.

Usage

const iter = arr.entries(); console.log(iter.next().value);--------for (let i of iter) { console.log(i)}

22
Q

Array.prototype.every()

A

Array Instance Iteration Method

arr.every(callback[, thisArg])

Tests whether every element in the array passes the test implemented by the provided callback.

Parameters

  • callback - function to test for each element
    • currentValue - required - current element being processed in the array.
    • index - the index of the current element in the array being processed
    • array - the array upon which every was called on
  • thisArg - value to use as this when executing the callback function

Return

  • true if the callback function returns a truthy value for every element in the array, otherwise ` false`

Notes

  • Returns immediately upon the first time that false is returned from the callback.
  • callback operates only on assigned values, not deleted ones or ones that have never been assigned
  • If this value is not provided to every, undefined will be used as the this instead, although the usual rules apply for the ultimate observable this to use.
  • Length of array is sample upon calling every, so appended elements will not be visited. Also, element values that are changed before they are visited by every will present their new values to every.
  • For empty arrays, every will return true

Usage

[1,2,3,4].every(x => x >= 5); // false

23
Q

Array.prototype.filter()

A

Array Instance Iteration Method

arr.filter(callback[, thisArg])

Creates a new array with all elements that pass the test implemented by the callback.

Parameters

  • callback - tests each element of the array. Return true to have the element in the new array, otherwise return false.
    • currentValue - required - current element being processed in the array.
    • index - the index of the current element in the array being processed
    • array - the array upon which filter was called on
  • thisArg - value to use as this when executing callback

Return

  • A new array with the elements that pass the test.

Research mdn examples of searching an array, and filtering invalid JSON entries.

24
Q

Array.prototype.find()

A

Array Instance Iteration Method

arr.find(callback[, thisArg])

Returns the first element that satisfies the provided testing function. Otherwise undefined is returned.

Parameters

  • callback - function to execute on each element in the array
    • currentValue - required - current element being processed in the array.
    • index - the index of the current element in the array being processed
    • array - the array upon which find was called on
  • thisArg - value to use as this when executing the callback function

Return

  • A value in the array if an element passes the test, otherwise undefined

Notes

  • Returns immediately upon the first time that false is returned from the callback.
  • callback operates on all indexes, not just those that have assigned values. Can be inefficient for sparse arrays.

Usage

[1,2,3,4].find(x => x == 3); // 3

25
Q

Array.prototype.findIndex()

A

Array Instance Iteration Method

arr.findIndex(callback[, thisArg])

Returns the index of the first element in the array that satisfies the callback, otherwise -1 is returned.

Parameters

  • callback - function to execute on each element in the array.
    • currentValue - required - current element being processed in the array.
    • index - the index of the current element in the array being processed
    • array - the array upon which findIndex() was called on
  • thisArg - value to use as this when executing the callback function

Return

  • The index of the first element in the array which passes the callback, otherwise -1

Notes

  • callback operates on all indexes, not just those that have assigned values. Can be inefficient for sparse arrays.

Usage

[1,2,3,4].findIndex(x => x == 3); // 2

26
Q

Array.prototype.forEach

A

Array Instance Iteration Method

arr.forEach(callback[, thisArg])

Executes a provided callback once for each element in the array.

Parameters

  • callback - function to execute for each element
    • currentValue - required - current element being processed in the array.
    • index - the index of the current element in the array being processed
    • array - the array upon which forEach was called on
  • thisArg - value to use as this when executing the callback function

Return

  • undefined

Notes

  • Always returns undefined and is not chainable.
  • Typical use case is to execute side effects at the end of a chain
  • There’s no way to stop or break a forEach() loop other than throwing an exception. Use another tool if you will need to break out.

Usage

[1,2,3,4].find(x => x == 3); // 3

Research copying an object, mdn on forEach() page

27
Q

Array.prototype.keys()

A

Array Instance Iteration Method

arr.keys()

Returns a new Array Iterator object that contains keys for each index of the array.

Return

  • A new Array Iterator object.

Notes

  • Doesn’t ignore holds in the array.

Usage

const keys = [...[3,2,5].keys()]console.log(keys) // [0, 1, 2]

28
Q

Array.prototype.map()

A

Array Instance Iteration Method

arr.map(callback[, thisArg])

Creates a new array with the results of calling a provided callback on every element of the calling array.

Parameters

  • callback - function that produces an element of the new array
    • currentValue - required - current element being processed in the array.
    • index - the index of the current element in the array being processed
    • array - the array upon which map() was called on
  • thisArg - value to use as this when executing the callback function

Return

  • A new array with each element being the result of the callback function.

Notes

  • map() only operates on indexes that have been assigned, including undefined
  • If array that map() was called on is sparse, resulting array will be sparse too.

Usage

var numbers = [1, 4, 9];var roots = numbers.map(Math.sqrt);['1','2','3'].map(Number) // [1,2,3]

29
Q

Array.prototype.reduce()

A

Array Instance Iteration Method

arr.reduce(callback[, initialValue])

A function is applied to an accumulator by way of each element in the array to reduce it to a single value.

Parameters

  • callback - function to execute on each element in the array
    • accumulator - the accumulation containing the previous return value, or initialValue if provided for the first call of callback.
    • currentValue - the current element being processed in the array
    • currentIndex - the index of the current element being processed in the array. Starts at index 0 if initialValue is provided, otherwise starts at 1.
    • array - the array upon which reduce() was called on
  • initialValue - optional - value to use as the first argument to the first call of the callback. If not provided, the first element in the array will be used instead for the first argument (accumulator)

Return

  • The resulting value from the reduction.

Notes

  • Does not operate on holes in the array.
  • If the array is empty and no initialValue is provided, TypeError will be thrown.
  • If either, a) the array has only one element and no initialValue is provided, or b) the array is empty and initialValue is provided: the solo element will be returned without calling callback.

Usage

Use -Infinity and Infinity for Math.max() and Math.min() methods within reduce to eliminate the multitude of return value possibilities that arise when failing to provide an initialValue

A map()/reduce() solution, with an initialValue is usually better practice to account for lone elements being return, or TypeErrors thrown because of nothing to operate on.

30
Q

Array.prototype.reduceRight()

A

Array Instance Iteration Method

arr.reduceRight(callback[, initialValue])

A function is applied to an accumulator by way of each element in the array to reduce it to a single value from right-to-left.

Parameters

  • callback - function to execute on each element in the array
    • accumulator - the accumulation containing the previous return value, or initialValue if provided for the first call of callback.
    • currentValue - the current element being processed in the array
    • currentIndex - the index of the current element being processed in the array. Starts at index 0 if initialValue is provided, otherwise starts at 1.
    • array - the array upon which reduceRight() was called on
  • initialValue - optional - value to use as the first argument to the first call of the callback. If not provided, the first element in the array will be used instead for the first argument (accumulator)

Return

  • The resulting value from the reduction.

Notes

  • Does not operate on holes in the array.
  • If the array is empty and no initialValue is provided, TypeError will be thrown.
  • If either, a) the array has only one element and no initialValue is provided, or b) the array is empty and initialValue is provided: the solo element will be returned without calling callback.

Usage

Use -Infinity and Infinity for Math.max() and Math.min() methods within reduce to eliminate the multitude of return value possibilities that arise when failing to provide an initialValue

A map()/reduce() solution, with an initialValue is usually better practice to account for lone elements being return, or TypeErrors thrown because of nothing to operate on.

31
Q

Array.prototype.some()

A

Array Instance Iteration Method

arr.some(callback[, thisArg])

Tests whether at least one element in the array passes the test implemented by the callback

Parameters

  • callback - function to test for each element
    • currentValue - required - current element being processed in the array.
    • index - the index of the current element in the array being processed
    • array - the array upon which some() was called
  • thisArg - value to use as this when executing the callback function

Return

  • true if the callback function returns a truthy value for any element in the array, otherwise ` false`

Notes

  • Returns immediately upon the first time that true is returned from the callback.
  • callback operates only on assigned values, not deleted ones or ones that have never been assigned
  • If this value is not provided to some(), undefined will be used as the this instead, although the usual rules apply for the ultimate observable this to use.
  • Length of array is sample upon calling every, so appended elements will not be visited. Also, element values that are changed before they are visited by every will present their new values to every.
  • For empty arrays, some() will return false. Different than every().

Usage

[1,2,3,4].some(x => x >= 5); // false

32
Q

Array.prototype.values()

A

Array Instance Iteration Method

arr.values()

Returns a new Array Iterator object that contains values for each index of the array.

Return

  • A new Array Iterator object.

Notes

  • Doesn’t ignore holds in the array.
  • Terrible compatibility, don’t use

Usage

const keys = [...[3,2,5].keys()]console.log(keys) // [0, 1, 2]

Research Array.prototype@@iterator

33
Q

Array Instance Mutator Methods

A

Methods that modify the array:

copyWithin()

fill()

pop()

push()

reverse()

shift()

sort()

splice()

unshift()

34
Q

Array Instance Accessor Methods

A

Methods that do not modify the array and return some representation of the array:

concat()

includes()

indexOf()

join()

lastIndexOf()

slice()

toString()

toLocaleString()

35
Q

Array Instance Iteration Methods

A

Methods that take function arguments to be called while processing the array:

  • the length is sampled beforehand - any additions will not be visited during iteration
  • changing/updating the array during iteration may introduce unintended bugs
    • if you must mutate the array, copy into a new array instead

entries()

every()

filter()

find()

findIndex()

forEach()

keys()

map()

reduce()

reduceRight()

some()

values()

36
Q

Array Static Methods

A

Static methods on the Array class:

from()

isArray()

of()