JavaScript Array Methods Cheat Sheet

Basic Array Methods

Method Returns Example Mutates
push() New length arr.push(5)
pop() Removed element arr.pop()
shift() Removed element arr.shift()
unshift() New length arr.unshift(1)
splice() Removed elements arr.splice(1, 2)
slice() New array arr.slice(1, 3)
concat() New array arr.concat([4, 5])
join() String arr.join('-')

map()

  • Transforms each item in the array.
  • Commonly used for changing values or extracting properties.
  • Returns a new array without modifying the original.
const numbers = [1, 2, 3, 4, 5];

// Double each number
const doubled = numbers.map(n => n * 2);

// Transform objects
const users = [
    { name: 'John', age: 30 },
    { name: 'Jane', age: 25 }
];
const names = users.map(user => user.name);

// With index
const indexed = numbers.map((n, i) => `${i}: ${n}`);

filter()

  • Keeps only items that match a condition.
  • Useful for removing unwanted data.
  • Returns a new array.
const numbers = [1, 2, 3, 4, 5, 6];

// Filter even numbers
const evens = numbers.filter(n => n % 2 === 0);

// Filter objects
const users = [
    { name: 'John', age: 30, active: true },
    { name: 'Jane', age: 25, active: false },
    { name: 'Bob', age: 35, active: true }
];
const activeUsers = users.filter(user => user.active);

// Multiple conditions
const adults = users.filter(user => user.age >= 18 && user.active);

reduce()

  • Reduces the array to a single value.
  • Common for sums, maximums, grouping, and flattening.
  • Can build custom output structures.
const numbers = [1, 2, 3, 4, 5];

// Sum all numbers
const sum = numbers.reduce((acc, n) => acc + n, 0);

// Find maximum
const max = numbers.reduce((acc, n) => Math.max(acc, n), -Infinity);

// Group by property
const users = [
    { name: 'John', age: 30, city: 'NYC' },
    { name: 'Jane', age: 25, city: 'LA' },
    { name: 'Bob', age: 35, city: 'NYC' }
];
const groupedByCity = users.reduce((acc, user) => {
    if (!acc[user.city]) acc[user.city] = [];
    acc[user.city].push(user);
    return acc;
}, {});

// Flatten arrays
const nested = [[1, 2], [3, 4], [5]];
const flattened = nested.reduce((acc, arr) => acc.concat(arr), []);

find() and findIndex()

  • find() returns the first match.
  • findIndex() returns the index of the first match.
  • Useful when you need just one item or its position.
const users = [
    { id: 1, name: 'John', age: 30 },
    { id: 2, name: 'Jane', age: 25 },
    { id: 3, name: 'Bob', age: 35 }
];

// Find first user over 30
const over30 = users.find(user => user.age > 30);

// Find index of user named Jane
const janeIndex = users.findIndex(user => user.name === 'Jane');

// Fallback if not found
const notFound = users.find(user => user.age > 50) || { name: 'Not found' };

some() and every()

  • some() checks if any item matches.
  • every() checks if all items match.
  • Good for quick condition checks.
const numbers = [2, 4, 6, 8, 10];

// Any odd number?
const hasOdd = numbers.some(n => n % 2 !== 0);

// All even numbers?
const allEven = numbers.every(n => n % 2 === 0);

// Any user is an admin?
const users = [
    { name: 'John', role: 'user' },
    { name: 'Jane', role: 'admin' },
    { name: 'Bob', role: 'user' }
];
const hasAdmin = users.some(user => user.role === 'admin');

includes() and indexOf()

  • includes() checks if an item exists in the array.
  • indexOf() returns the position or -1 if not found.
  • Fast and easy lookup methods.
const fruits = ['apple', 'banana', 'orange'];

// Check existence
const hasApple = fruits.includes('apple');
const hasGrape = fruits.includes('grape');

// Find position
const bananaIndex = fruits.indexOf('banana');
const grapeIndex = fruits.indexOf('grape');

// Start search from specific index
const hasOrangeAfterIndex1 = fruits.includes('orange', 2);

sort()

  • Sorts values in-place (mutates original array).
  • Can sort numbers, strings, or objects with a function.
  • Default sort is string-based.
const numbers = [3, 1, 4, 1, 5, 9];

// Sort ascending
const sorted = numbers.sort((a, b) => a - b);

// Sort descending
const reverseSorted = numbers.sort((a, b) => b - a);

// Sort strings
const names = ['Charlie', 'Alice', 'Bob'];
const sortedNames = names.sort();

// Sort objects
const users = [
    { name: 'John', age: 30 },
    { name: 'Jane', age: 25 },
    { name: 'Bob', age: 35 }
];
const sortedByAge = users.sort((a, b) => a.age - b.age);
const sortedByName = users.sort((a, b) => a.name.localeCompare(b.name));

reverse()

  • Reverses the order of elements.
  • Modifies the original array.
  • Use slice().reverse() to keep original intact.
const numbers = [1, 2, 3, 4, 5];
const reversed = numbers.reverse();

const original = [1, 2, 3, 4, 5];
const reversedCopy = original.slice().reverse();

forEach()

  • Runs a function for each item in the array.
  • Does not return a new array.
  • Ideal for side effects like logging or external updates.
const numbers = [1, 2, 3, 4, 5];

// Basic loop
numbers.forEach(n => console.log(n));

// With index
numbers.forEach((n, i) => console.log(`${i}: ${n}`));

// External mutation
let sum = 0;
numbers.forEach(n => sum += n);

for...of Loop

  • Loop that works well with arrays.
  • Use .entries() to get index and value.
  • Supports break and continue.
const numbers = [1, 2, 3, 4, 5];

for (const num of numbers) {
    console.log(num);
}

for (const [index, value] of numbers.entries()) {
    console.log(`${index}: ${value}`);
}

for (const num of numbers) {
    if (num > 3) break;
    console.log(num);
}

Array.from()

  • Converts things to arrays (strings, Sets).
  • Can map values while creating the array.
const chars = Array.from('hello');
const unique = Array.from(new Set([1, 2, 2, 3]));
const doubled = Array.from([1, 2, 3], x => x * 2);
const range = Array.from({ length: 5 }, (_, i) => i);

Spread Operator

  • Spreads elements into a new array.
  • Useful for merging, cloning, inserting, or spreading into functions.
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const combined = [...arr1, ...arr2];
const copy = [...arr1];
const withInsert = [...arr1, 2.5, ...arr2];
const max = Math.max(...arr1);

Destructuring

  • Pulls out values from arrays by position.
  • Can skip or collect remaining values.
  • Also useful for swapping and default values.
const numbers = [1, 2, 3, 4, 5];

const [first, second] = numbers;
const [a, , c] = numbers;
const [head, ...tail] = numbers;
const [x, y, z = 0] = [1, 2];
let a = 1, b = 2;
[a, b] = [b, a];

Array Methods with Objects

  • Great for grouping, calculating totals, and filtering complex data.
const products = [
    { id: 1, name: 'Laptop', price: 999, category: 'electronics' },
    { id: 2, name: 'Book', price: 15, category: 'books' },
    { id: 3, name: 'Phone', price: 699, category: 'electronics' }
];

const byCategory = products.reduce((acc, product) => {
    if (!acc[product.category]) acc[product.category] = [];
    acc[product.category].push(product);
    return acc;
}, {});

const totalByCategory = products.reduce((acc, product) => {
    acc[product.category] = (acc[product.category] || 0) + product.price;
    return acc;
}, {});

const expensive = products.filter(p => p.price > 500);

Performance Considerations

  • Avoid unnecessary nested loops.
  • Use Set for fast existence checks in large arrays.
const numbers = [1, 2, 3, 4, 5];

const inefficient = numbers.map(n => {
    return numbers.filter(m => m < n).length;
});

const efficient = numbers.map(n => numbers.filter(m => m < n).length);

const largeArray = Array.from({ length: 10000 }, (_, i) => i);
const lookupSet = new Set(largeArray);
const hasValue = lookupSet.has(5000);