Here's a cheatsheet of some common JavaScript array methods:
-
Array.prototype.push([item1, ..., itemN])
Adds one or more elements to the end of an array and returns the new length of the array.
let arr = [1, 2, 3];
arr.push(4);
Results: [1, 2, 3, 4]
-
Array.prototype.pop()
Removes the last element from an array and returns that element.
let arr = [1, 2, 3, 4];
let lastItem = arr.pop();
Results: 4
(lastItem), [1, 2, 3]
(arr)
-
Array.prototype.shift()
Removes the first element from an array and returns that removed element.
let arr = [1, 2, 3, 4];
let firstItem = arr.shift();
Results: 1
(firstItem), [2, 3, 4]
(arr)
-
Array.prototype.unshift([item1, ..., itemN])
Adds one or more elements to the beginning of an array and returns the new length of the array.
let arr = [1, 2, 3];
arr.unshift(0);
Results: [0, 1, 2, 3]
-
Array.prototype.slice([start?, end?])
Returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included).
let arr = [1, 2, 3, 4];
let subArr = arr.slice(1, 3);
Results: [2, 3]
(subArr)
-
Array.prototype.splice(start, deleteCount, [item1, ..., itemN])
Changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
let arr = [1, 2, 3, 4];
arr.splice(1, 2, 'a', 'b');
Results: [1, 'a', 'b', 4]
-
Array.prototype.sort([compareFunction])
Sorts the elements of an array in place and returns the array.
let arr = [3, 1, 4, 1];
arr.sort(((a, b) => a - b));
Results: [1, 1, 3, 4]
-
Array.prototype.reverse()
Reverses an array in place.
let arr = [1, 2, 3, 4];
arr.reverse();
Results: [4, 3, 2, 1]
-
Array.prototype.indexOf(searchElement[, fromIndex])
Returns the first index at which a given element can be found in the array, or -1 if it is not present.
let arr = [1, 2, 3, 4];
let index = arr.indexOf(3);
Results: 2
(index)
-
Array.prototype.includes(searchElement[, fromIndex])
Determines whether an array includes a certain value among its entries, returning true or false as appropriate.
let arr = [1, 2, 3, 4];
let hasThree = arr.includes(3);
Results: true
(hasThree)
-
Array.prototype.filter(callback[, thisArg])
Creates a new array with all elements that pass the test implemented by the provided function.
let arr = [1, 2, 3, 4];
let isEven = arr.filter(num => num % 2 === 0);
Results: [2, 4]
(isEven)
-
Array.prototype.map(callback[, thisArg])
Creates a new array with the results of calling a provided function on every element in the calling array.
let arr = [1, 2, 3, 4];
let squares = arr.map(num => num * num);
Results: [1, 4, 9, 16]
(squares)
-
Array.prototype.reduce(callback[, initialValue])
Apply a function against an accumulator and each element in the array (from left to right) to reduce it to a single output value.
let arr = [1, 2, 3, 4];
let sum = arr.reduce((acc, num) => acc + num, 0);
Results: 10
(sum)
Top comments (0)