Back to Resources
JavaScript Arrays Cheat Sheet
The Ultimate guide to mutating and iterating through arrays in JavaScript.
1. Iteration Methods (Modern ES6)
The best ways to loop through array elements cleanly.
Array.prototype.forEach()
Executes a provided function once for each array element. Does not return a new array.
const numbers = [1, 2, 3];
numbers.forEach(num => console.log(num)); // 1, 2, 3Array.prototype.map()
Creates a new array populated with the results of calling a provided function on every element.
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
// doubled is [2, 4, 6]Array.prototype.filter()
Creates a shallow copy containing only elements that pass the test implemented by the provided function.
const ages = [12, 18, 24, 7];
const adults = ages.filter(age => age >= 18);
// adults is [18, 24]2. Mutating Arrays
Methods that change the array in place.
push(items): Adds one or more elements to the end of an array.pop(): Removes the last element from an array.shift(): Removes the first element from an array.unshift(items): Adds one or more elements to the front of an array.splice(start, count, items): Changes the contents of an array by removing or replacing existing elements and/or adding new elements.
3. Searching Arrays
Quickly find items within your arrays.
find(callback): Returns the first element that satisfies the testing function.findIndex(callback): Returns the index of the first element that satisfies the test.includes(value): Determines whether an array includes a certain value (returns boolean).indexOf(value): Returns the first index at which a given element can be found, or -1 if it is not present.