Arrays Flashcards
Array.from()
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 asthis
when executingmapFn
Return
A new array instance
Notes
- Lets you create
Array
s from:- array-like objects
- those with a
length
property and indexed elements likearguments
orNodeList
- those with a
- iterable objects
- objects that have implemented the
@@iterator
method, likeMap
,Set
,String
,Array
- objects that have implemented the
- array-like objects
- This is the official replacement for
[].slice.call(arrLike)
-
Array.from(obj, mapFn, thisArg)
has same result asArray.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 newUint8Array
- Not creating an intermediate array is useful if you were doing
- Converts holes to value
undefined
U - 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
- For creating new array from iterable objects, use spread syntax instead
<small>Research HTMLCollection, FileList, NodeList - all these elements that are array-like</small>
Array.isArray()
Array Static Method
Array.isArray(obj)
Parameters
-
obj
- the object to be checked
Return
-
true
if array; otherwisefalse
Notes
- Always use
Array.isArray()
rather thaninstanceof
becauseinstanceof
does not work through iframes - Always returns
false
for instances ofTypedArray
Array.of()
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 newArray
with one element of which it’s value is 3.[3]
-
Array(3)
will create an emptyArray
oflength
3. - Polyfill is simply:
Array.prototype.slice.call(arguments)
Array.prototype.copyWithin()
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 thanarr.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 includingend
element. If negative, counted from end. If omitted, will copy to the end (default toarr.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.
Array.prototype.fill()
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 tothis.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
Array.prototype.pop()
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
- be careful for a value in the array being
Array.prototype.push()
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 usingconcat()
–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
- Must be careful. We easily run the risk of going over the limit of
- 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
- Would increment (or create) the
Array.prototype.reverse()
Array Instance Mutator Method
arr.reverse()
Reverses an array in place
Returns
- The reversed array.
Array.prototype.shift()
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
, returnedundefined
doesn’t necessarily mean empty array
- again, note that a value could be
Notes
- Removes element at 0-th index and consecutively shifts indexes down throughout the rest of the array.
Array.prototype.sort()
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
- use this over
-
- If
compareFunction(a,b)
returns less than 0, sorta
at a lower index thanb
- 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 anothermap
usingreturn originalArray[el.index]
-
because thecompareFunction
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 amap
-
Study numeric overflow
Array.prototype.splice()
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 fromstart
to end of array will be deleted -
item1, item2, ...
- Elements to add to the array starting at thestart
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
is0
or negative, no elements are removed - If
start
isNaN
, will be treated as0
Array.prototype.unshift()
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.
Array.prototype.concat()
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
Array.prototype.includes()
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 forsearchElement
. If negative, searches from that absolute value beforearr.length
Return
- A
Boolean
Notes
- If
fromIndex
is>=
length of array, thenfalse
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.
Array.prototype.indexOf()
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.
Array.prototype.join()
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
ornull
, it’s converted to an empty string.
Array.prototype.lastIndexOf()
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
===
Array.prototype.slice()
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 toarr.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])`
Array.prototype.toString()
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.
Array.prototype.toLocaleString()
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.
Array.prototype.entries()
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)}
Array.prototype.every()
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 whichevery
was called on
-
-
thisArg
- value to use asthis
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 toevery
,undefined
will be used as thethis
instead, although the usual rules apply for the ultimate observablethis
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 byevery
will present their new values toevery
. -
For empty arrays,
every
will returntrue
Usage
[1,2,3,4].every(x => x >= 5); // false
Array.prototype.filter()
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. Returntrue
to have the element in the new array, otherwise returnfalse
.-
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 whichfilter
was called on
-
-
thisArg
- value to use asthis
when executingcallback
Return
- A new array with the elements that pass the test.
Research mdn examples of searching an array, and filtering invalid JSON entries.
Array.prototype.find()
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 whichfind
was called on
-
-
thisArg
- value to use asthis
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
Array.prototype.findIndex()
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 whichfindIndex()
was called on
-
-
thisArg
- value to use asthis
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
Array.prototype.forEach
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 whichforEach
was called on
-
-
thisArg
- value to use asthis
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
Array.prototype.keys()
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]
Array.prototype.map()
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 whichmap()
was called on
-
-
thisArg
- value to use asthis
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, includingundefined
- 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]
Array.prototype.reduce()
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, orinitialValue
if provided for the first call ofcallback
. -
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 ifinitialValue
is provided, otherwise starts at 1. -
array
- the array upon whichreduce()
was called on
-
-
initialValue
- optional - value to use as the first argument to the first call of thecallback
. 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 andinitialValue
is provided: the solo element will be returned without callingcallback
.
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 TypeError
s thrown because of nothing to operate on.
Array.prototype.reduceRight()
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, orinitialValue
if provided for the first call ofcallback
. -
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 ifinitialValue
is provided, otherwise starts at 1. -
array
- the array upon whichreduceRight()
was called on
-
-
initialValue
- optional - value to use as the first argument to the first call of thecallback
. 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 andinitialValue
is provided: the solo element will be returned without callingcallback
.
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 TypeError
s thrown because of nothing to operate on.
Array.prototype.some()
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 whichsome()
was called
-
-
thisArg
- value to use asthis
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 tosome()
,undefined
will be used as thethis
instead, although the usual rules apply for the ultimate observablethis
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 byevery
will present their new values toevery
. -
For empty arrays,
some()
will returnfalse
. Different thanevery()
.
Usage
[1,2,3,4].some(x => x >= 5); // false
Array.prototype.values()
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
Array Instance Mutator Methods
Methods that modify the array:
copyWithin()
fill()
pop()
push()
reverse()
shift()
sort()
splice()
unshift()
Array Instance Accessor Methods
Methods that do not modify the array and return some representation of the array:
concat()
includes()
indexOf()
join()
lastIndexOf()
slice()
toString()
toLocaleString()
Array Instance Iteration Methods
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()
Array Static Methods
Static methods on the Array class:
from()
isArray()
of()