Arrays API Flashcards

1
Q

Array.prototype.forEach()

A

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.

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

Array.prototype.map()

A

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.

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

Syntax of the filter() array method

A

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.

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

Array.prototype.sort()

A

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 be undefined.
  • b - The second element for comparison. Will never be undefined.

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).

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

Array.prototype.toSorted()

A

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.

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

Array.prototype.splice()

A

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 (and splice() is called with no arguments), nothing is deleted. This is different from passing undefined, which is converted to 0.
  • 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 by start, then all the elements from start to the end of the array will be deleted.
    • If deleteCount is 0 or negative, no elements are removed. In this case, you should specify at least one new element
  • 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.

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

Array.prototype.toSpliced()

A

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 (and splice() is called with no arguments), nothing is deleted. This is different from passing undefined, which is converted to 0.
  • 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 by start, then all the elements from start to the end of the array will be deleted.
    • If deleteCount is 0 or negative, no elements are removed. In this case, you should specify at least one new element
  • 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.

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

Array.prototype[@@iterator]()

A

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.

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

Array.prototype.at()

A

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.

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

Array.prototype.with()

A

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.

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

Array.prototype.copyWithin()

A

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 after start after normalization, copying only happens until the end of array.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 or end 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]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Array.prototype.every()

A

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 array every() 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.

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

Array.prototype.fill()

A

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 or start 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 or end is omitted, array.length is used, causing all indices until the end to be filled.
  • If end is positioned before or at start 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" }]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Array.prototype.find()

A

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)

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 array find() 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.

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

Array.prototype.findIndex()

A

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 array findIndex() 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.

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

Array.prototype.findLast()

A

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)

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 array findLast() 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.

17
Q

Array.prototype.findLastIndex()

A

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 array findLastIndex() 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.

18
Q

Array.prototype.flat()

A

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 to 1.

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]
19
Q

Array.prototype.flatMap()

A

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)

Parameters
callbackFn - 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 array flatMap() 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"]
20
Q

Array.from()

A

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)

Parameters
arrayLike - 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" ]
21
Q

Array.fromAsync()

A

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)

Parameters
arrayLike - 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]
22
Q

Array.prototype.reduce()

A

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 to callbackFn. On the first call, its value is initialValue if the latter is specified; otherwise its value is array[0].
  • currentValue - The value of the current element. On the first call, its value is array[0] if initialValue is specified; otherwise its value is array[1].
  • currentIndex - The index position of currentValue in the array. On the first call, its value is 0 if initialValue is specified, otherwise 1.
  • array - The array reduce() 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.

23
Q

Array.prototype.reduceRight()

A

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

24
Q

Array.of

A

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]