JavaScript Array Methods - Complete Cheat Sheet
Master JavaScript array methods with practical examples. From map and filter to reduce and forEach, learn all essential array manipulation techniques.
JavaScript Array Methods - Complete Cheat Sheet
JavaScript arrays come with powerful built-in methods that make data manipulation easy and efficient. Here's your complete guide to essential array methods with practical examples.
Basic Array Methods #
Adding/Removing Elements #
const fruits = ['apple', 'banana'];
// Add to end
fruits.push('orange'); // ['apple', 'banana', 'orange']
// Add to beginning
fruits.unshift('grape'); // ['grape', 'apple', 'banana', 'orange']
// Remove from end
const lastFruit = fruits.pop(); // 'orange'
// Remove from beginning
const firstFruit = fruits.shift(); // 'grape'
// Add/remove at specific position
fruits.splice(1, 1, 'kiwi'); // Remove 1 item at index 1, add 'kiwi'
// ['apple', 'kiwi', 'banana']
Iterating Methods #
forEach - Execute function for each element #
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((num, index) => {
console.log(`Index ${index}: ${num}`);
});
// With traditional function
numbers.forEach(function(num) {
console.log(num * 2);
});
map - Transform each element #
const numbers = [1, 2, 3, 4, 5];
// Double each number
const doubled = numbers.map(num => num * 2);
// [2, 4, 6, 8, 10]
// Transform objects
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 }
];
const userNames = users.map(user => user.name);
// ['Alice', 'Bob']
const userInfo = users.map(user => ({
...user,
isAdult: user.age >= 18
}));
filter - Select elements that pass a test #
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Get even numbers
const evenNumbers = numbers.filter(num => num % 2 === 0);
// [2, 4, 6, 8, 10]
// Filter objects
const users = [
{ name: 'Alice', age: 25, active: true },
{ name: 'Bob', age: 17, active: false },
{ name: 'Carol', age: 30, active: true }
];
const activeAdults = users.filter(user => user.age >= 18 && user.active);
// [{ name: 'Alice', age: 25, active: true }, { name: 'Carol', age: 30, active: true }]
reduce - Reduce array to single value #
const numbers = [1, 2, 3, 4, 5];
// Sum all numbers
const sum = numbers.reduce((total, num) => total + num, 0);
// 15
// Find maximum
const max = numbers.reduce((max, num) => num > max ? num : max, numbers[0]);
// 5
// Group objects
const people = [
{ name: 'Alice', department: 'Engineering' },
{ name: 'Bob', department: 'Sales' },
{ name: 'Carol', department: 'Engineering' }
];
const groupedByDept = people.reduce((groups, person) => {
const dept = person.department;
if (!groups[dept]) {
groups[dept] = [];
}
groups[dept].push(person);
return groups;
}, {});
Search Methods #
find - Find first element that matches #
const users = [
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' },
{ id: 3, name: 'Carol', email: 'carol@example.com' }
];
// Find user by ID
const user = users.find(u => u.id === 2);
// { id: 2, name: 'Bob', email: 'bob@example.com' }
// Returns undefined if not found
const notFound = users.find(u => u.id === 999);
// undefined
findIndex - Find index of first matching element #
const numbers = [10, 20, 30, 40, 50];
const index = numbers.findIndex(num => num > 25);
// 2 (index of 30)
// Returns -1 if not found
const notFoundIndex = numbers.findIndex(num => num > 100);
// -1
includes - Check if array contains value #
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.includes('banana')); // true
console.log(fruits.includes('grape')); // false
// Case sensitive
console.log(fruits.includes('Apple')); // false
indexOf/lastIndexOf - Find index of value #
const numbers = [1, 2, 3, 2, 4, 2];
console.log(numbers.indexOf(2)); // 1 (first occurrence)
console.log(numbers.lastIndexOf(2)); // 5 (last occurrence)
console.log(numbers.indexOf(99)); // -1 (not found)
Testing Methods #
some - Test if at least one element passes test #
const numbers = [1, 2, 3, 4, 5];
// Check if any number is even
const hasEven = numbers.some(num => num % 2 === 0);
// true
// Check if any number > 10
const hasLarge = numbers.some(num => num > 10);
// false
every - Test if all elements pass test #
const numbers = [2, 4, 6, 8];
// Check if all numbers are even
const allEven = numbers.every(num => num % 2 === 0);
// true
// Check if all numbers > 5
const allLarge = numbers.every(num => num > 5);
// false
Transformation Methods #
sort - Sort array elements #
// Sort numbers (beware: converts to strings by default)
const numbers = [3, 1, 4, 1, 5, 9];
// Wrong way (sorts as strings)
numbers.sort(); // [1, 1, 3, 4, 5, 9] - works for single digits
// Right way for numbers
numbers.sort((a, b) => a - b); // Ascending
numbers.sort((a, b) => b - a); // Descending
// Sort objects
const users = [
{ name: 'Charlie', age: 30 },
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 35 }
];
// Sort by name
users.sort((a, b) => a.name.localeCompare(b.name));
// Sort by age
users.sort((a, b) => a.age - b.age);
reverse - Reverse array order #
const numbers = [1, 2, 3, 4, 5];
numbers.reverse(); // [5, 4, 3, 2, 1]
// Note: reverse() modifies original array
// For immutable version:
const reversed = [...numbers].reverse();
Advanced Methods #
flat - Flatten nested arrays #
const nested = [1, [2, 3], [4, [5, 6]]];
console.log(nested.flat()); // [1, 2, 3, 4, [5, 6]]
console.log(nested.flat(2)); // [1, 2, 3, 4, 5, 6] - depth 2
console.log(nested.flat(Infinity)); // Flatten all levels
flatMap - Map then flatten #
const words = ['hello', 'world'];
// Split each word into characters and flatten
const chars = words.flatMap(word => word.split(''));
// ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
// Equivalent to:
const charsManual = words.map(word => word.split('')).flat();
join - Convert array to string #
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.join()); // "apple,banana,orange"
console.log(fruits.join(', ')); // "apple, banana, orange"
console.log(fruits.join(' | ')); // "apple | banana | orange"
slice - Extract section of array #
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.slice(1, 3)); // [2, 3] - from index 1 to 3 (exclusive)
console.log(numbers.slice(2)); // [3, 4, 5] - from index 2 to end
console.log(numbers.slice(-2)); // [4, 5] - last 2 elements
// slice doesn't modify original array
console.log(numbers); // [1, 2, 3, 4, 5]
Method Chaining #
Combine multiple array methods for powerful data transformations:
const sales = [
{ product: 'Laptop', amount: 1200, month: 'Jan' },
{ product: 'Phone', amount: 800, month: 'Jan' },
{ product: 'Laptop', amount: 1200, month: 'Feb' },
{ product: 'Tablet', amount: 500, month: 'Feb' },
{ product: 'Phone', amount: 800, month: 'Mar' }
];
// Find total sales for laptops and phones over $700
const totalHighValueSales = sales
.filter(sale => ['Laptop', 'Phone'].includes(sale.product))
.filter(sale => sale.amount > 700)
.map(sale => sale.amount)
.reduce((total, amount) => total + amount, 0);
console.log(totalHighValueSales); // 4000
Performance Tips #
- Use
forloops for simple iterations when performance is critical - Chain methods efficiently - filter before map when possible
- Use
some()/every()instead offilter().lengthfor existence checks - Consider
Setfor unique values instead of complex filtering
Quick Reference #
| Method | Returns | Mutates Original | Use Case |
|---|---|---|---|
forEach | undefined | No | Execute function for each element |
map | New array | No | Transform each element |
filter | New array | No | Select elements by condition |
reduce | Any value | No | Reduce to single value |
find | Element or undefined | No | Find first matching element |
some | boolean | No | Test if any element passes |
every | boolean | No | Test if all elements pass |
sort | Same array | Yes | Sort elements |
reverse | Same array | Yes | Reverse order |
push/pop | Length/Element | Yes | Add/remove from end |
slice | New array | No | Extract section |
splice | Removed elements | Yes | Add/remove at position |
Summary #
JavaScript array methods provide powerful tools for data manipulation:
- Iteration:
forEach,map,filter,reduce - Search:
find,findIndex,includes,indexOf - Testing:
some,every - Transformation:
sort,reverse,flat,join - Modification:
push,pop,shift,unshift,splice
Master these methods to write cleaner, more functional JavaScript code!