Arrays API Flashcards
Array.prototype.forEach()
Syntax
forEach(callbackFn) forEach(callbackFn, thisArg)
Parameters
callbackFn
- A function to execute for each element in the array. Its return value is discarded. The function is called with the following arguments:
-
element
- The current element being processed in the array. -
index
- The index of the current element being processed in the array. -
array
-The array forEach() was called upon.
thisArg
Optional - A value to use as this when executing callbackFn.
“Array.prototype.forEach() - JavaScript | MDN” (MDN Web Docs). Retrieved November 9, 2023.
Array.prototype.map()
Syntax
map(callbackFn) map(callbackFn, thisArg)
Parameters
callbackFn
- A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments:
-
element
- The current element being processed in the array. -
index
- The index of the current element being processed in the array. - ‘array` - The array map() was called upon.
thisArg
Optional - A value to use as this when executing callbackFn.
Return value
A new array with each element being the result of the callback function.
“Array.prototype.map() - JavaScript | MDN” (MDN Web Docs). Retrieved November 10, 2023.
Syntax of the filter()
array method
Syntax
filter(callbackFn) filter(callbackFn, thisArg)
Parameters
callbackFn
- A function to execute for each element in the array. It should return a truthy value to keep the element in the resulting array, and a falsy value otherwise. The function is called with the following arguments:
-
element
- The current element being processed in the array. -
index
- The index of the current element being processed in the array. -
array
- The array filter() was called upon.
thisArg
Optional - A value to use as this when executing callbackFn.
Return value
A shallow copy of the given array containing just the elements that pass the test. If no elements pass the test, an empty array is returned.
“Array.prototype.filter() - JavaScript | MDN” (MDN Web Docs). Retrieved November 10, 2023.
Array.prototype.sort()
The sort()
method of Array instances sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
Note: to sort the elements in an array without mutating the original array, use toSorted()
.
Syntax
sort() sort(compareFn)
Parameters
compareFn
Optional - A function that defines the sort order. The return value should be a number
whose sign indicates the relative order of the two elements: negative if a
is less than b
, positive if a
is greater than b
, and zero if they are equal. NaN
is treated as 0
. The function is called with the following arguments:
-
a
- The first element for comparison. Will never beundefined
. -
b
- The second element for comparison. Will never beundefined
.
If omitted, the array elements are converted to strings, then sorted according to each character’s Unicode code point value.
Return value
The reference to the original array, now sorted. Note that the array is sorted in place, and no copy is made.
Notes
The sort()
method preserves empty slots. If the source array is sparse, the empty slots are moved to the end of the array, and always come after all the undefined
.
If compareFn
is supplied, all non-undefined
array elements are sorted according to the return value of the compare function (all undefined
elements are sorted to the end of the array, with no call to compareFn
).
“Array.prototype.sort() - JavaScript | MDN” (MDN Web Docs). Retrieved December 1, 2023.
Array.prototype.toSorted()
The toSorted()
method of Array
instances is the copying version of the sort()
method. It returns a new array with the elements sorted in ascending order.
Syntax
toSorted() toSorted(compareFn)
Parameters
compareFn
Optional - Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character’s Unicode code point value.
-
a
- The first element for comparison. -
b
- The second element for comparison.
NOTE: Empty slots are sorted as if they have the value undefined
. They are always sorted to the end of the array and compareFn
is not called for them.
“Array.prototype.toSorted() - JavaScript | MDN” (MDN Web Docs). Retrieved December 1, 2023.
Array.prototype.splice()
The splice()
method of Array instances changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
To create a new array with a segment removed and/or replaced without mutating the original array, use toSpliced()
.
Syntax
splice(start) splice(start, deleteCount) splice(start, deleteCount, item1) splice(start, deleteCount, item1, item2) splice(start, deleteCount, item1, item2, /* …, */ itemN)
Parameters
-
start
- Zero-based index at which to start changing the array, converted to an integer.- Negative index counts back from the end of the array — if
start < 0
,start + array.length
is used. - If
start < -array.length
,0
is used. - If
start >= array.length
, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided. - If
start
is omitted (andsplice()
is called with no arguments), nothing is deleted. This is different from passingundefined
, which is converted to0
.
- Negative index counts back from the end of the array — if
-
deleteCount
Optional - An integer indicating the number of elements in the array to remove fromstart
.- If
deleteCount
is omitted, or if its value is greater than or equal to the number of elements after the position specified bystart
, then all the elements from start to the end of the array will be deleted. - If
deleteCount
is0
or negative, no elements are removed. In this case, you should specify at least one new element
- If
-
item1, …, itemN
Optional - The elements to add to the array, beginning from start. If you do not specify any elements,splice()
will only remove elements from the array.
Return value
An array containing the deleted elements.
If only one element is removed, an array of one element is returned.
If no elements are removed, an empty array is returned.
“Array.prototype.splice() - JavaScript | MDN” (MDN Web Docs). Retrieved December 1, 2023.
Array.prototype.toSpliced()
The toSpliced()
method of Array instances is the copying version of the splice()
method. It returns a new array with some elements removed and/or replaced at a given index.
Syntax
toSplice(start) toSplice(start, deleteCount) toSplice(start, deleteCount, item1) toSplice(start, deleteCount, item1, item2) toSplice(start, deleteCount, item1, item2, /* …, */ itemN)
Parameters
-
start
- Zero-based index at which to start changing the array, converted to an integer.- Negative index counts back from the end of the array — if
start < 0
,start + array.length
is used. - If
start < -array.length
,0
is used. - If
start >= array.length
, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided. - If
start
is omitted (andsplice()
is called with no arguments), nothing is deleted. This is different from passingundefined
, which is converted to0
.
- Negative index counts back from the end of the array — if
-
deleteCount
Optional - An integer indicating the number of elements in the array to remove from start.- If
deleteCount
is omitted, or if its value is greater than or equal to the number of elements after the position specified bystart
, then all the elements from start to the end of the array will be deleted. - If
deleteCount
is0
or negative, no elements are removed. In this case, you should specify at least one new element
- If
-
item1, …, itemN Optional - The elements to add to the array, beginning from
start
. If you do not specify any elements,toSplice()
will only remove elements from the array.
Return value
An array containing the deleted elements.
If only one element is removed, an array of one element is returned.
If no elements are removed, an empty array is returned.
“Array.prototype.toSpliced() - JavaScript | MDN” (MDN Web Docs). Retrieved December 1, 2023.
Array.prototype[@@iterator]()
The [@@iterator]()
method of Array instances implements the iterable protocol and allows arrays to be consumed by most syntaxes expecting iterables, such as the spread syntax and for...of
loops. It returns an array iterator object that yields the value of each index in the array.
The initial value of this property is the same function object as the initial value of the Array.prototype.values
property.
Syntax
array[Symbol.iterator]()
Parameters
None.
Return value
The same return value as Array.prototype.values()
: a new iterable iterator object that yields the value of each index in the array.
“Array.prototype[@@iterator]() - JavaScript | MDN” (MDN Web Docs). Retrieved December 11, 2023.
Array.prototype.at()
The at()
method of Array instances takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.
Syntax
at(index)
Parameters
index
- Zero-based index of the array element to be returned, converted to an integer. Negative index counts back from the end of the array — if index < 0, index + array.length
is accessed.
Return value
The element in the array matching the given index. Always returns undefined
if index < -array.length
or index >= array.length
without attempting to access the corresponding property.
NOTE: The at()
method is generic. It only expects the this
value to have a length
property and integer-keyed properties.
“Array.prototype.at() - JavaScript | MDN” (MDN Web Docs). Retrieved December 18, 2023.
Array.prototype.with()
The with()
method of Array instances is the copying version of using the bracket notation to change the value of a given index. It returns a new array with the element at the given index replaced with the given value.
Syntax
arrayInstance.with(index, value)
Parameters
index
- Zero-based index at which to change the array, converted to an integer.
- Negative index counts back from the end of the array — if
index < 0, index + array.length
is used. - If the index after normalization is out of bounds, a
RangeError
is thrown.
value
- Any value to be assigned to the given index.
Return value
A new array with the element at index replaced with value.
Exceptions
RangeError
Thrown if index >= array.length or index < -array.length
.
“Array.prototype.with() - JavaScript | MDN” (MDN Web Docs). Retrieved December 18, 2023.
Array.prototype.copyWithin()
The copyWithin()
method of Array instances shallow copies part of this array to another location in the same array and returns this array without modifying its length.
The copyWithin()
is a high-performance method to shift the data of an Array.
The copyWithin()
does not alter the length
of this
, but it will change the content of this
and create new properties or delete existing properties, if necessary.
The copyWithin()
method preserves empty slots.
The copyWithin()
method is generic. It only expects the this
value to have a length
property and integer-keyed properties. Although strings
are also array-like, this method is not suitable to be applied on them, as strings are immutable.
Syntax
copyWithin(target, start) copyWithin(target, start, end)
Parameters
target
- Zero-based index at which to copy the sequence to, converted to an integer. This corresponds to where the element at start
will be copied to, and all elements between start
and end are copied to succeeding indices.
- Negative index counts back from the end of the array — if
target < 0
,target + array.length
is used. - If
target < -array.length
,0
is used. - If
target >= array.length
, nothing is copied. - If
target
is positioned afterstart
after normalization, copying only happens until the end ofarray.length
(in other words,copyWithin()
never extends the array).
start
- Zero-based index at which to start copying elements from, converted to an integer.
- Negative index counts back from the end of the array — if
start < 0
,start + array.length
is used. - If
start < -array.length
,0
is used. - If
start >= array.length
, nothing is copied.
end
Optional - Zero-based index at which to end copying elements from, converted to an integer. copyWithin()
copies up to but not including end.
- Negative index counts back from the end of the array — if
end < 0
,end + array.length
is used. - If
end < -array.length
,0
is used. - If
end >= array.length
orend
is omitted,array.length
is used, causing all elements until the end to be copied. - If end is positioned before or at
start
after normalization, nothing is copied.
Return value
The modified array.
Examples:
console.log([1, 2, 3, 4, 5].copyWithin(0, 3)); // [4, 5, 3, 4, 5] console.log([1, 2, 3, 4, 5].copyWithin(0, 3, 4)); // [4, 2, 3, 4, 5] console.log([1, 2, 3, 4, 5].copyWithin(-2, -3, -1)); // [1, 2, 3, 3, 4]
“Array.prototype.copyWithin() - JavaScript | MDN” (MDN Web Docs). Retrieved December 19, 2023.
Array.prototype.every()
The every()
method of Array instances tests whether all elements in the array pass the test implemented by the provided function. It returns a boolean value.
Syntax
every(callbackFn) every(callbackFn, thisArg)
Parameters
callbackFn
- A function to execute for each element in the array. It should return a truthy value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments:
-
element
- The current element being processed in the array. -
index
- The index of the current element being processed in the array. -
array
- The arrayevery()
was called upon.
thisArg
Optional - A value to use as this when executing callbackFn
.
Return value
true
unless callbackFn
returns a falsy value for an array element, in which case false
is immediately returned.
“Array.prototype.every() - JavaScript | MDN” (MDN Web Docs). Retrieved December 19, 2023.
Array.prototype.fill()
The fill()
method of Array instances changes all elements within a range of indices in an array to a static value. It returns the modified array.
Syntax
fill(value) fill(value, start) fill(value, start, end)
Parameters
value
- Value to fill the array with. Note all elements in the array will be this exact value: if value
is an object, each slot in the array will reference that object.
start
Optional - Zero-based index at which to start filling, converted to an integer.
- Negative index counts back from the end of the array — if
start < 0
,start + array.length
is used. - If
start < -array.length
orstart
is omitted,0
is used. - If
start >= array.length
, no index is filled.
end
Optional - Zero-based index at which to end filling, converted to an integer. fill()
fills up to but not including end.
- Negative index counts back from the end of the array — if
end < 0
,end + array.length
is used. - If
end < -array.length
,0
is used. -
If end >= array.length
orend
is omitted,array.length
is used, causing all indices until the end to be filled. - If
end
is positioned before or atstart
after normalization, no index is filled.
Return value
The modified array, filled with value.
Examples:
console.log([1, 2, 3].fill(4)); // [4, 4, 4] console.log([1, 2, 3].fill(4, 1)); // [1, 4, 4] console.log([1, 2, 3].fill(4, 1, 2)); // [1, 4, 3] console.log([1, 2, 3].fill(4, 1, 1)); // [1, 2, 3] console.log([1, 2, 3].fill(4, 3, 3)); // [1, 2, 3] console.log([1, 2, 3].fill(4, -3, -2)); // [4, 2, 3] console.log([1, 2, 3].fill(4, NaN, NaN)); // [1, 2, 3] console.log([1, 2, 3].fill(4, 3, 5)); // [1, 2, 3] console.log(Array(3).fill(4)); // [4, 4, 4] // A single object, referenced by each slot of the array: const arr = Array(3).fill({}); // [{}, {}, {}] arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]
“Array.prototype.fill() - JavaScript | MDN” (MDN Web Docs). Retrieved December 20, 2023.
Array.prototype.find()
The find()
method of Array instances returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined
is returned.
Syntax
find(callbackFn) find(callbackFn, thisArg)
ParameterscallbackFn
- A function to execute for each element in the array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:
-
element
- The current element being processed in the array. -
index
- The index of the current element being processed in the array. -
array
- The arrayfind()
was called upon.
thisArg
Optional - A value to use as this
when executing callbackFn
.
Return value
The first element in the array that satisfies the provided testing function. Otherwise, undefined
is returned.
“Array.prototype.find() - JavaScript | MDN” (MDN Web Docs). Retrieved December 20, 2023.
Array.prototype.findIndex()
The findIndex()
method of Array instances returns the index
of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1
is returned.
Syntax
findIndex(callbackFn) findIndex(callbackFn, thisArg)
Parameters
callbackFn
- A function to execute for each element in the array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:
-
element
- The current element being processed in the array. -
index
- The index of the current element being processed in the array. -
array
- The arrayfindIndex()
was called upon.
thisArg
Optional - A value to use as this
when executing callbackFn.
Return value
The index of the first element in the array that passes the test. Otherwise, -1
.
“Array.prototype.findIndex() - JavaScript | MDN” (MDN Web Docs). Retrieved December 20, 2023.
Array.prototype.findLast()
The findLast()
method of Array instances iterates the array in reverse order and returns the value of the first element that satisfies the provided testing function. If no elements satisfy the testing function, undefined
is returned.
Syntax
findLast(callbackFn) findLast(callbackFn, thisArg)
ParameterscallbackFn
- A function to execute for each element in the array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:
-
element
- The current element being processed in the array. -
index
- The index of the current element being processed in the array. -
array
- The arrayfindLast()
was called upon.
thisArg Optional
A value to use as this when executing callbackFn
.
Return value
The last (highest-index) element in the array that satisfies the provided testing function; undefined
if no matching element is found.
“Array.prototype.findLast() - JavaScript | MDN” (MDN Web Docs). Retrieved December 20, 2023.
Array.prototype.findLastIndex()
The findLastIndex()
method of Array instances iterates the array in reverse order and returns the index of the first element that satisfies the provided testing function. If no elements satisfy the testing function, -1
is returned.
Syntax
findLastIndex(callbackFn) findLastIndex(callbackFn, thisArg)
Parameters
callbackFn
- A function to execute for each element in the array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:
-
element
- The current element being processed in the array. -
index
- The index of the current element being processed in the array. -
array
- The arrayfindLastIndex()
was called upon.
thisArg
Optional - A value to use as this when executing callbackFn
.
Return value
The index of the last (highest-index) element in the array that passes the test. Otherwise -1
if no matching element is found.
“Array.prototype.findLastIndex() - JavaScript | MDN” (MDN Web Docs). Retrieved December 21, 2023.
Array.prototype.flat()
The flat()
method of Array instances creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
The flat()
method is a copying method. It does not alter this but instead returns a shallow copy that contains the same elements as the ones from the original array.
Syntax
flat() flat(depth)
Parameters
-
depth
Optional - The depth level specifying how deep a nested array structure should be flattened. Defaults to1
.
Return value
A new array with the sub-array elements concatenated into it.
Examples
const arr1 = [1, 2, [3, 4]]; arr1.flat(); // [1, 2, 3, 4] const arr2 = [1, 2, [3, 4, [5, 6]]]; arr2.flat(); // [1, 2, 3, 4, [5, 6]] const arr3 = [1, 2, [3, 4, [5, 6]]]; arr3.flat(2); // [1, 2, 3, 4, 5, 6] const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]; arr4.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
“Array.prototype.flat() - JavaScript | MDN” (MDN Web Docs). Retrieved December 21, 2023.
Array.prototype.flatMap()
The flatMap()
method of Array instances returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a map()
followed by a flat()
of depth 1
(arr.map(...args).flat()
), but slightly more efficient than calling those two methods separately.
Syntax
flatMap(callbackFn) flatMap(callbackFn, thisArg)
ParameterscallbackFn
- A function to execute for each element in the array. It should return an array containing new elements of the new array, or a single non-array value to be added to the new array. The function is called with the following arguments:
-
element
- The current element being processed in the array. -
index
- The index of the current element being processed in the array. -
array
- The arrayflatMap()
was called upon.
thisArg
Optional - A value to use as this when executing callbackFn.
Return value
A new array with each element being the result of the callback function and flattened by a depth of 1
.
Examples
const arr1 = ["it's Sunny in", "", "California"]; arr1.map((x) => x.split(" ")); // [["it's","Sunny","in"],[""],["California"]] arr1.flatMap((x) => x.split(" ")); // ["it's","Sunny","in", "", "California"]
“Array.prototype.flatMap() - JavaScript | MDN” (MDN Web Docs). Retrieved December 21, 2023.
Array.from()
The Array.from()
static method creates a new, shallow-copied Array instance from an iterable or array-like object.
Syntax
Array.from(arrayLike) Array.from(arrayLike, mapFn) Array.from(arrayLike, mapFn, thisArg)
ParametersarrayLike
- An iterable or array-like object to convert to an array.
mapFn
Optional - A function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and mapFn
’s return value is added to the array instead. The function is called with the following arguments:
-
element
- The current element being processed in the array. -
index
- The index of the current element being processed in the array.
thisArg
Optional - Value to use as this
when executing mapFn
.
Return value
A new Array instance.
Examples
Array.from("foo"); // [ "f", "o", "o" ] const set = new Set(["foo", "bar", "baz", "foo"]); Array.from(set); // [ "foo", "bar", "baz" ]
“Array.from() - JavaScript | MDN” (MDN Web Docs). Retrieved December 21, 2023.
Array.fromAsync()
The Array.fromAsync()
static method creates a new, shallow-copied Array instance from an async iterable (objects such as ReadableStream and AsyncGenerator), iterable (objects such as Map and Set, or array-like object (objects with a length property and indexed elements)..
Syntax
Array.fromAsync(arrayLike) Array.fromAsync(arrayLike, mapFn) Array.fromAsync(arrayLike, mapFn, thisArg)
ParametersarrayLike
- An async iterable, iterable, or array-like object to convert to an array.
mapFn
Optional - A function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and mapFn
’s return value is added to the array instead (after being awaited). The function is called with the following arguments:
-
element
- The current element being processed in the array. Because all elements are first awaited, this value will never be a thenable. -
index
- The index of the current element being processed in the array.
thisArg
Optional - Value to use as this
when executing mapFn
.
Return value
A new Promise whose fulfillment value is a new Array instance.
Examples
// Array from an async iterable const asyncIterable = (async function* () { for (let i = 0; i < 5; i++) { await new Promise((resolve) => setTimeout(resolve, 10 * i)); yield i; } })(); Array.fromAsync(asyncIterable).then((array) => console.log(array)); // [0, 1, 2, 3, 4] function delayedValue(v) { return new Promise((resolve) => setTimeout(() => resolve(v), 100)); } // Using mapFn Array.fromAsync( [delayedValue(1), delayedValue(2), delayedValue(3)], (element) => delayedValue(element * 2), ).then((array) => console.log(array)); // [2, 4, 6]
Array.prototype.reduce()
The reduce()
method of Array instances executes a user-supplied “reducer” callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
The first time that the callback is run there is no “return value of the previous calculation”. If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).
Syntax
reduce(callbackFn) reduce(callbackFn, initialValue)
Parameters
callbackFn
- A function to execute for each element in the array. Its return value becomes the value of the accumulator parameter on the next invocation of callbackFn
. For the last invocation, the return value becomes the return value of reduce()
. The function is called with the following arguments:
-
accumulator
- The value resulting from the previous call tocallbackFn
. On the first call, its value isinitialValue
if the latter is specified; otherwise its value isarray[0]
. -
currentValue
- The value of the current element. On the first call, its value isarray[0]
ifinitialValue
is specified; otherwise its value isarray[1]
. -
currentIndex
- The index position ofcurrentValue
in the array. On the first call, its value is0
ifinitialValue
is specified, otherwise1
. -
array
- The arrayreduce()
was called upon.
initialValue
Optional - A value to which accumulator
is initialized the first time the callbackFn
is called. If initialValue is specified, callbackFn
starts executing with the first value in the array as currentValue. If initialValue
is not specified, accumulator is initialized to the first value in the array, and callbackFn starts
executing with the second value in the array as currentValue. In this case, if the array is empty (so that there’s no first value to return as accumulator), an error is thrown.
Return value
The value that results from running the “reducer” callback function to completion over the entire array.
Exceptions
TypeError
- Thrown if the array contains no elements and initialValue is not provided.
“Array.prototype.reduce() - JavaScript | MDN” (MDN Web Docs). Retrieved January 2, 2024.
Array.prototype.reduceRight()
reduceRight()
method of Array instances applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.
It works exactly as Array.prototype.reduce()
but it goes over the array in reverse order.
The first time that the callback is run there is no “return value of the previous calculation”. If supplied, an initial value may be used in its place. Otherwise the last array element is used as the initial value and iteration starts from the previous element
“Array.prototype.reduceRight() - JavaScript | MDN” (MDN Web Docs). Retrieved January 2, 2024.
Array.of
The Array.of()
static method creates a new Array instance from a variable number of arguments, regardless of number or type of the arguments.
Syntax
Array.of() Array.of(element1) Array.of(element1, element2) Array.of(element1, element2, /* …, */ elementN)
Parameters
-
element1, …, elementN
- Elements used to create the array.
Return value
A new Array instance.
Examples
Array.of(1); // [1] Array.of(1, 2, 3); // [1, 2, 3] Array.of(undefined); // [undefined]
“Array.of() - JavaScript | MDN” (MDN Web Docs). Retrieved January 3, 2024.