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.