JS Array Methods Flashcards

1
Q

Array.prototype.indexOf()

A

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Syntax
indexOf(searchElement)
indexOf(searchElement, fromIndex)

Examples
Using indexOf()
The following example uses indexOf() to locate values in an array.

const array = [2, 9, 9];
array.indexOf(2); // 0
array.indexOf(7); // -1
array.indexOf(9, 2); // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0

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

Array.prototype.push()

A

The push() method adds one or more elements to the end of an array and returns the new length of the array.

Syntax
push(element0)
push(element0, element1)
push(element0, element1, /* … ,*/ elementN)

Examples
Adding elements to an array
The following code creates the sports array containing two elements, then appends two elements to it. The total variable contains the new length of the array.

const sports = [‘soccer’, ‘baseball’];
const total = sports.push(‘football’, ‘swimming’);

console.log(sports); // [‘soccer’, ‘baseball’, ‘football’, ‘swimming’]
console.log(total); // 4

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

Array.prototype.unshift()

A

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

Syntax
unshift(element0)
unshift(element0, element1)
unshift(element0, element1, /* … ,*/ elementN)

Examples
Using unshift()
const arr = [1, 2];

arr.unshift(0); // result of the call is 3, which is the new array length
// arr is [0, 1, 2]

arr.unshift(-2, -1); // the new array length is 5
// arr is [-2, -1, 0, 1, 2]

arr.unshift([-4, -3]); // the new array length is 6
// arr is [[-4, -3], -2, -1, 0, 1, 2]

arr.unshift([-7, -6], [-5]); // the new array length is 8
// arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]

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

Array.prototype.pop()

A

The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

Syntax
pop()

Examples
Removing the last element of an array
The following code creates the myFish array containing four elements, then removes its last element.

const myFish = [‘angel’, ‘clown’, ‘mandarin’, ‘sturgeon’];

const popped = myFish.pop();

console.log(myFish); // [‘angel’, ‘clown’, ‘mandarin’ ]

console.log(popped); // ‘sturgeon’

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

Array.prototype.shift()

A

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

Syntax
shift()

Examples
Removing an element from an array
The following code displays the myFish array before and after removing its first element. It also displays the removed element:

const myFish = [‘angel’, ‘clown’, ‘mandarin’, ‘surgeon’];

console.log(‘myFish before:’, JSON.stringify(myFish));
// myFish before: [‘angel’, ‘clown’, ‘mandarin’, ‘surgeon’]

const shifted = myFish.shift();

console.log(‘myFish after:’, myFish);
// myFish after: [‘clown’, ‘mandarin’, ‘surgeon’]

console.log(‘Removed this element:’, shifted);
// Removed this element: angel

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

Array.prototype.splice()

A

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice().

Syntax
splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2, itemN)

Examples
Remove 0 (zero) elements before index 2, and insert “drum”
const myFish = [‘angel’, ‘clown’, ‘mandarin’, ‘sturgeon’];
const removed = myFish.splice(2, 0, ‘drum’);

// myFish is [“angel”, “clown”, “drum”, “mandarin”, “sturgeon”]
// removed is [], no elements removed

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

for…of

A

The for…of executes a loop that operates on a sequence of values sourced from an iterable object. Iterable objects include instances of built-ins such as Array, String, TypedArray, Map, Set, NodeList (and other DOM collections), as well as the arguments object, generators produced by generator functions, and user-defined iterables.

Syntax
for (variable of iterable)
statement

Examples
Iterating over an Array
const iterable = [10, 20, 30];

for (const value of iterable) {
console.log(value);
}
// 10
// 20
// 30

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

Array.prototype.map()

A

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

Syntax
// Arrow function
map((element) => { /* … / })
map((element, index) => { /
/ })
map((element, index, array) => { /
… */ })

// Callback function
map(callbackFn)
map(callbackFn, thisArg)

// Inline callback function
map(function(element) { /* … / })
map(function(element, index) { /
/ })
map(function(element, index, array){ /
/ })
map(function(element, index, array) { /
… */ }, thisArg)

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

Array.prototype.filter()

A

The filter() method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.

Syntax
// Arrow function
filter((element) => { /* … / } )
filter((element, index) => { /
/ } )
filter((element, index, array) => { /
… */ } )

// Callback function
filter(callbackFn)
filter(callbackFn, thisArg)

// Inline callback function
filter(function(element) { /* … / })
filter(function(element, index) { /
/ })
filter(function(element, index, array){ /
/ })
filter(function(element, index, array) { /
… */ }, thisArg)

Examples
Filtering out all small values
The following example uses filter() to create a filtered array that has all elements with values less than 10 removed.

function isBigEnough(value) {
return value >= 10;
}

const filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

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

Array.prototype.toString()

A

The toString() method returns a string representing the specified array and its elements.

Syntax
toString()

Examples
Using toString
const array1 = [1, 2, ‘a’, ‘1a’];

console.log(array1.toString());
// expected output: “1,2,a,1a”

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

Array.prototype.join()

A

The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

Syntax
join()
join(separator)

Examples
Joining an array four different ways
The following example creates an array, a, with three elements, then joins the array four times: using the default separator, then a comma and a space, then a plus and an empty string.

const a = [‘Wind’, ‘Water’, ‘Fire’];
a.join(); // ‘Wind,Water,Fire’
a.join(‘, ‘); // ‘Wind, Water, Fire’
a.join(‘ + ‘); // ‘Wind + Water + Fire’
a.join(‘’); // ‘WindWaterFire’

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

Array.prototype.some()

A

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn’t modify the array.

Syntax
// Arrow function
some((element) => { /* … / } )
some((element, index) => { /
/ } )
some((element, index, array) => { /
… */ } )

// Callback function
some(callbackFn)
some(callbackFn, thisArg)

// Inline callback function
some(function(element) { /* … / })
some(function(element, index) { /
/ })
some(function(element, index, array){ /
/ })
some(function(element, index, array) { /
… */ }, thisArg)

Examples
Testing value of array elements
The following example tests whether any element in the array is bigger than 10.

function isBiggerThan10(element, index, array) {
return element > 10;
}

[2, 5, 8, 1, 4].some(isBiggerThan10); // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true

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

Array.prototype.every()

A

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

Syntax
// Arrow function
every((element) => { /* … / } )
every((element, index) => { /
/ } )
every((element, index, array) => { /
… */ } )

// Callback function
every(callbackFn)
every(callbackFn, thisArg)

// Inline callback function
every(function(element) { /* … / })
every(function(element, index) { /
/ })
every(function(element, index, array){ /
/ })
every(function(element, index, array) { /
… */ }, thisArg)

Examples
Testing size of all array elements
The following example tests whether all elements in the array are bigger than 10.

function isBigEnough(element, index, array) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); // false
[12, 54, 18, 130, 44].every(isBigEnough); // true

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

Array.from()

A

The Array.from() static method creates a new, shallow-copied Array instance from an iterable or array-like object.

Syntax
// Arrow function
Array.from(arrayLike, (element) => { /* … / } )
Array.from(arrayLike, (element, index) => { /
… */ } )

// Mapping function
Array.from(arrayLike, mapFn)
Array.from(arrayLike, mapFn, thisArg)

// Inline mapping function
Array.from(arrayLike, function mapFn(element) { /* … / })
Array.from(arrayLike, function mapFn(element, index) { /
/ })
Array.from(arrayLike, function mapFn(element) { /
/ }, thisArg)
Array.from(arrayLike, function mapFn(element, index) { /
… */ }, thisArg)

Examples
Array from a String
Array.from(‘foo’);
// [ “f”, “o”, “o” ]

Array from a Set
const set = new Set([‘foo’, ‘bar’, ‘baz’, ‘foo’]);
Array.from(set);
// [ “foo”, “bar”, “baz” ]

Array from a Map
const map = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(map);
// [[1, 2], [2, 4], [4, 8]]

const mapper = new Map([[‘1’, ‘a’], [‘2’, ‘b’]]);
Array.from(mapper.values());
// [‘a’, ‘b’];

Array.from(mapper.keys());
// [‘1’, ‘2’];

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

Array.prototype.flat()

A

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

Syntax
flat()
flat(depth)

Examples
Flattening nested arrays
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]

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

Array.prototype.findIndex()

A

The findIndex() method 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
// Arrow function
findIndex((element) => { /* … / } )
findIndex((element, index) => { /
/ } )
findIndex((element, index, array) => { /
… */ } )

// Callback function
findIndex(callbackFn)
findIndex(callbackFn, thisArg)

// Inline callback function
findIndex(function(element) { /* … / })
findIndex(function(element, index) { /
/ })
findIndex(function(element, index, array){ /
/ })
findIndex(function(element, index, array) { /
… */ }, thisArg)

Examples
Find the index of a prime number in an array
The following example returns the index of the first element in the array that is a prime number, or -1 if there is no prime number.

function isPrime(element) {
if (element % 2 === 0 || element < 2) {
return false;
}
for (let factor = 3; factor <= Math.sqrt(element); factor += 2) {
if (element % factor === 0) {
return false;
}
}
return true;
}

console.log([4, 6, 8, 9, 12].findIndex(isPrime)); // -1, not found
console.log([4, 6, 7, 9, 12].findIndex(isPrime)); // 2 (array[2] is 7)

17
Q

Array.prototype.find()

A

The find() method 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
// Arrow function
find((element) => { /* … / } )
find((element, index) => { /
/ } )
find((element, index, array) => { /
… */ } )

// Callback function
find(callbackFn)
find(callbackFn, thisArg)

// Inline callback function
find(function(element) { /* … / })
find(function(element, index) { /
/ })
find(function(element, index, array){ /
/ })
find(function(element, index, array) { /
… */ }, thisArg)

Examples
Find an object in an array by one of its properties
const inventory = [
{name: ‘apples’, quantity: 2},
{name: ‘bananas’, quantity: 0},
{name: ‘cherries’, quantity: 5}
];

function isCherries(fruit) {
return fruit.name === ‘cherries’;
}

console.log(inventory.find(isCherries));
// { name: ‘cherries’, quantity: 5 }

18
Q

Array.prototype.sort()

A

The sort() method 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.

The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.

Syntax
// Functionless
sort()

// Arrow function
sort((a, b) => { /* … */ } )

// Compare function
sort(compareFn)

// Inline compare function
sort(function compareFn(a, b) { /* … */ })

Examples
Creating, displaying, and sorting an array
The following example creates four arrays and displays the original array, then the sorted arrays. The numeric arrays are sorted without a compare function, then sorted using one.

const stringArray = [‘Blue’, ‘Humpback’, ‘Beluga’];
const numberArray = [40, 1, 5, 200];
const numericStringArray = [‘80’, ‘9’, ‘700’];
const mixedNumericArray = [‘80’, ‘9’, ‘700’, 40, 1, 5, 200];

function compareNumbers(a, b) {
return a - b;
}

stringArray.join(); // ‘Blue,Humpback,Beluga’
stringArray.sort(); // [‘Beluga’, ‘Blue’, ‘Humpback’]

numberArray.join(); // ‘40,1,5,200’
numberArray.sort(); // [1, 200, 40, 5]
numberArray.sort(compareNumbers); // [1, 5, 40, 200]

numericStringArray.join(); // ‘80,9,700’
numericStringArray.sort(); // [‘700’, ‘80’, ‘9’]
numericStringArray.sort(compareNumbers); // [‘9’, ‘80’, ‘700’]

mixedNumericArray.join(); // ‘80,9,700,40,1,5,200’
mixedNumericArray.sort(); // [1, 200, 40, 5, ‘700’, ‘80’, ‘9’]
mixedNumericArray.sort(compareNumbers); // [1, 5, ‘9’, 40, ‘80’, 200, ‘700’]

19
Q

Array.prototype.reverse()

A

The reverse() method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated.

Syntax
reverse()

Examples
Reversing the elements in an array
The following example creates an array items, containing three elements, then reverses the array. The call to reverse() returns a reference to the reversed array items.

const items = [1, 2, 3];
console.log(items); // [1, 2, 3]

items.reverse();
console.log(items); // [3, 2, 1]

20
Q

Array.prototype.concat()

A

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

Syntax
concat()
concat(value0)
concat(value0, value1)
concat(value0, value1, /* … ,*/ valueN)

Examples
Concatenating two arrays
The following code concatenates two arrays:

const letters = [‘a’, ‘b’, ‘c’];
const numbers = [1, 2, 3];

const alphaNumeric = letters.concat(numbers);
console.log(alphaNumeric);
// results in [‘a’, ‘b’, ‘c’, 1, 2, 3]

21
Q

Array.prototype.fill()

A

The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It returns the modified array.

Syntax
fill(value)
fill(value, start)
fill(value, start, end)

Examples
Using fill
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]
console.log([].fill.call({ length: 3 }, 4)); // {0: 4, 1: 4, 2: 4, length: 3}

// 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” }]

22
Q

Array.prototype.includes()

A

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

Syntax
includes(searchElement)
includes(searchElement, fromIndex)

Examples
[1, 2, 3].includes(2) // true
[1, 2, 3].includes(4) // false
[1, 2, 3].includes(3, 3) // false
[1, 2, 3].includes(3, -1) // true
[1, 2, NaN].includes(NaN) // true
[“1”, “2”, “3”].includes(3) // false