JS Array Methods Flashcards
Array.prototype.indexOf()
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
Array.prototype.push()
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
Array.prototype.unshift()
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 ]
Array.prototype.pop()
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’
Array.prototype.shift()
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
Array.prototype.splice()
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
for…of
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
Array.prototype.map()
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)
Array.prototype.filter()
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]
Array.prototype.toString()
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”
Array.prototype.join()
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’
Array.prototype.some()
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
Array.prototype.every()
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
Array.from()
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’];
Array.prototype.flat()
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]