JavaScript Array Functions Cheatsheet: A Developer's Guide

Arrays are fundamental building blocks in JavaScript, and mastering array methods can significantly improve your coding efficiency. In this comprehensive guide, we’ll explore the most useful array functions with practical examples that you can start using in your projects today.

Table of Contents #

Adding and Removing Elements #

Let’s start with the basics of manipulating array contents. These methods are the foundation of array operations in JavaScript.

push() and pop() #

The push() method adds elements to the end of an array, while pop() removes the last element. These methods modify the original array in place.

const fruits = ['apple', 'banana'];

// Adding elements
fruits.push('orange');  // Returns 3 (new length)
console.log(fruits);    // ['apple', 'banana', 'orange']

// Removing elements
const lastFruit = fruits.pop();  // Returns 'orange'
console.log(fruits);            // ['apple', 'banana']

// You can push multiple elements at once
fruits.push('mango', 'grape', 'kiwi');
console.log(fruits);  // ['apple', 'banana', 'mango', 'grape', 'kiwi']

When to use: push() and pop() are perfect for implementing stack data structures or when you need to work with the end of an array efficiently.

unshift() and shift() #

Similar to push and pop, but these methods work from the beginning of the array. Note that these operations are generally slower than push/pop because they require shifting all existing elements.

const numbers = [2, 3];

// Adding to the start
numbers.unshift(1);     // Returns 3 (new length)
console.log(numbers);   // [1, 2, 3]

// Removing from the start
const firstNumber = numbers.shift();  // Returns 1
console.log(numbers);                // [2, 3]

// Adding multiple elements at the start
numbers.unshift(-2, -1, 0);
console.log(numbers);  // [-2, -1, 0, 2, 3]

Performance note: For large arrays, consider using push() and then reverse() if you need better performance, as unshift() has O(n) complexity.

Transforming Arrays #

These methods help you create new arrays based on existing ones, which is essential for functional programming patterns.

map() #

The map() method creates a new array by transforming each element through a callback function. The original array remains unchanged.

const prices = [10, 20, 30];
const withTax = prices.map(price => price * 1.2);
console.log(withTax);  // [12, 24, 36]

// More complex transformations
const products = [
  { name: 'Laptop', price: 1000 },
  { name: 'Phone', price: 500 },
  { name: 'Tablet', price: 300 }
];

const productNames = products.map(product => product.name);
console.log(productNames);  // ['Laptop', 'Phone', 'Tablet']

// Using index parameter
const withPosition = prices.map((price, index) => ({
  position: index + 1,
  price: price
}));
console.log(withPosition);
// [{ position: 1, price: 10 }, { position: 2, price: 20 }, { position: 3, price: 30 }]

filter() #

Use filter() to create a new array containing only elements that pass a test condition. This is perfect for data filtering and validation.

const scores = [75, 48, 95, 60, 85];
const passingScores = scores.filter(score => score >= 60);
console.log(passingScores);  // [75, 95, 60, 85]

// Filtering objects
const users = [
  { name: 'John', age: 25, active: true },
  { name: 'Jane', age: 30, active: false },
  { name: 'Bob', age: 35, active: true }
];

const activeUsers = users.filter(user => user.active);
console.log(activeUsers);
// [{ name: 'John', age: 25, active: true }, { name: 'Bob', age: 35, active: true }]

// Combining conditions
const youngActiveUsers = users.filter(user => user.active && user.age < 30);
console.log(youngActiveUsers);  // [{ name: 'John', age: 25, active: true }]

reduce() #

The reduce() method is powerful for combining all array elements into a single value. It’s one of the most versatile array methods.

const transactions = [100, -50, 25, -15, 40];
const balance = transactions.reduce((sum, transaction) => sum + transaction, 0);
console.log(balance);  // 100

// Finding maximum value
const numbers = [5, 12, 8, 130, 44];
const max = numbers.reduce((max, num) => num > max ? num : max, numbers[0]);
console.log(max);  // 130

// Grouping data
const people = [
  { name: 'Alice', department: 'Engineering' },
  { name: 'Bob', department: 'Marketing' },
  { name: 'Charlie', department: 'Engineering' }
];

const byDepartment = people.reduce((acc, person) => {
  if (!acc[person.department]) {
    acc[person.department] = [];
  }
  acc[person.department].push(person.name);
  return acc;
}, {});
console.log(byDepartment);
// { Engineering: ['Alice', 'Charlie'], Marketing: ['Bob'] }

// Counting occurrences
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
const fruitCount = fruits.reduce((count, fruit) => {
  count[fruit] = (count[fruit] || 0) + 1;
  return count;
}, {});
console.log(fruitCount);  // { apple: 3, banana: 2, orange: 1 }

Searching and Sorting #

These methods help you find elements and organize your arrays efficiently.

find() and findIndex() #

The find() method returns the first element that matches a condition, while findIndex() returns its index. These are perfect for searching through arrays of objects.

const users = [
  { id: 1, name: 'John', email: 'john@example.com' },
  { id: 2, name: 'Jane', email: 'jane@example.com' },
  { id: 3, name: 'Bob', email: 'bob@example.com' }
];

const jane = users.find(user => user.name === 'Jane');
console.log(jane);  // { id: 2, name: 'Jane', email: 'jane@example.com' }

const janeIndex = users.findIndex(user => user.name === 'Jane');
console.log(janeIndex);  // 1

// Returns undefined if not found
const notFound = users.find(user => user.name === 'Alice');
console.log(notFound);  // undefined

// Returns -1 if index not found
const notFoundIndex = users.findIndex(user => user.name === 'Alice');
console.log(notFoundIndex);  // -1

indexOf() and lastIndexOf() #

For simple value searches, indexOf() and lastIndexOf() are faster than find().

const colors = ['red', 'blue', 'green', 'blue', 'yellow'];

console.log(colors.indexOf('blue'));      // 1 (first occurrence)
console.log(colors.lastIndexOf('blue'));  // 3 (last occurrence)
console.log(colors.indexOf('purple'));    // -1 (not found)

// Starting search from specific index
console.log(colors.indexOf('blue', 2));   // 3 (starts from index 2)

sort() #

The sort() method arranges array elements in place. Remember to provide a comparison function for numbers!

const fruits = ['banana', 'apple', 'orange', 'mango'];
fruits.sort();
console.log(fruits);  // ['apple', 'banana', 'mango', 'orange']

// Sorting numbers (important!)
const numbers = [23, 5, 100, 56, 9];
numbers.sort((a, b) => a - b);  // Ascending
console.log(numbers);  // [5, 9, 23, 56, 100]

// Descending order
numbers.sort((a, b) => b - a);
console.log(numbers);  // [100, 56, 23, 9, 5]

// Sorting objects
const products = [
  { name: 'Laptop', price: 1000 },
  { name: 'Phone', price: 500 },
  { name: 'Tablet', price: 750 }
];

products.sort((a, b) => a.price - b.price);
console.log(products);
// [{ name: 'Phone', price: 500 }, { name: 'Tablet', price: 750 }, { name: 'Laptop', price: 1000 }]

// Sorting strings case-insensitive
const names = ['John', 'alice', 'Bob', 'charlie'];
names.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
console.log(names);  // ['alice', 'Bob', 'charlie', 'John']

reverse() #

Reverses the array in place.

const numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers);  // [5, 4, 3, 2, 1]

Array Inspection Methods #

These methods help you examine array contents without modifying them.

includes() #

Check if an array contains a specific value. This is more readable than indexOf() !== -1.

const numbers = [1, 2, 3, 4, 5];

console.log(numbers.includes(3));     // true
console.log(numbers.includes(10));    // false

// You can specify starting index
console.log(numbers.includes(2, 2));  // false (starts from index 2)

// Works with NaN
const values = [1, NaN, 3];
console.log(values.includes(NaN));    // true

some() #

Returns true if at least one element satisfies the condition.

const numbers = [1, 2, 3, 4, 5];

const hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven);  // true

const hasNegative = numbers.some(num => num < 0);
console.log(hasNegative);  // false

// Checking for property existence
const users = [
  { name: 'John', admin: false },
  { name: 'Jane', admin: true },
  { name: 'Bob', admin: false }
];

const hasAdmin = users.some(user => user.admin);
console.log(hasAdmin);  // true

every() #

Check if all elements satisfy a condition.

const ages = [19, 21, 25, 18];
const allAdults = ages.every(age => age >= 18);
console.log(allAdults);  // true

const allOldEnough = ages.every(age => age >= 21);
console.log(allOldEnough);  // false

// Validating data
const products = [
  { name: 'Laptop', price: 1000 },
  { name: 'Phone', price: 500 },
  { name: 'Tablet', price: 300 }
];

const allHavePrices = products.every(product => product.price > 0);
console.log(allHavePrices);  // true

Slicing and Combining Arrays #

These methods help you work with portions of arrays or combine multiple arrays.

slice() #

Creates a new array from a portion of an existing array without modifying the original.

const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];

// Extract elements from index 2 to 4 (not including 4)
const spring = months.slice(2, 4);
console.log(spring);  // ['Mar', 'Apr']

// From index 3 to end
const lastMonths = months.slice(3);
console.log(lastMonths);  // ['Apr', 'May', 'Jun']

// Negative indices (from end)
const lastTwo = months.slice(-2);
console.log(lastTwo);  // ['May', 'Jun']

// Create a shallow copy
const monthsCopy = months.slice();
console.log(monthsCopy);  // ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']

splice() #

Modifies the original array by removing, replacing, or adding elements.

const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];

// Remove 2 elements starting from index 1
const removed = months.splice(1, 2);
console.log(removed);  // ['Feb', 'Mar']
console.log(months);   // ['Jan', 'Apr', 'May']

// Insert elements without removing
months.splice(1, 0, 'February', 'March');
console.log(months);   // ['Jan', 'February', 'March', 'Apr', 'May']

// Replace elements
months.splice(1, 2, 'Feb', 'Mar');
console.log(months);   // ['Jan', 'Feb', 'Mar', 'Apr', 'May']

// Remove all elements from index 2
months.splice(2);
console.log(months);   // ['Jan', 'Feb']

concat() #

Combines two or more arrays without modifying the original arrays.

const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [5, 6];

const combined = arr1.concat(arr2, arr3);
console.log(combined);  // [1, 2, 3, 4, 5, 6]

// Can also concat values
const withValues = arr1.concat(10, arr2, 20);
console.log(withValues);  // [1, 2, 10, 3, 4, 20]

Spread Operator (…) #

Modern alternative to concat with better readability.

const arr1 = [1, 2];
const arr2 = [3, 4];

// Combining arrays
const combined = [...arr1, ...arr2];
console.log(combined);  // [1, 2, 3, 4]

// Adding elements
const withExtra = [0, ...arr1, 2.5, ...arr2, 5];
console.log(withExtra);  // [0, 1, 2, 2.5, 3, 4, 5]

// Creating shallow copies
const copy = [...arr1];
console.log(copy);  // [1, 2]

// Spreading in function calls
const numbers = [1, 5, 3, 8, 2];
console.log(Math.max(...numbers));  // 8

join() #

Converts array elements to a string.

const words = ['Hello', 'World', '!'];
console.log(words.join(' '));   // 'Hello World !'
console.log(words.join('-'));   // 'Hello-World-!'
console.log(words.join(''));    // 'HelloWorld!'

const numbers = [1, 2, 3, 4, 5];
console.log(numbers.join(', '));  // '1, 2, 3, 4, 5'

Advanced Array Methods #

flat() #

Flattens nested arrays to a specified depth.

const nested = [1, [2, 3], [4, [5, 6]]];

console.log(nested.flat());     // [1, 2, 3, 4, [5, 6]] (depth 1 by default)
console.log(nested.flat(2));    // [1, 2, 3, 4, 5, 6] (depth 2)
console.log(nested.flat(Infinity));  // Flattens completely

// Removing empty slots
const withHoles = [1, 2, , 4, 5];
console.log(withHoles.flat());  // [1, 2, 4, 5]

flatMap() #

Combines map() and flat() in one operation.

const sentences = ['Hello world', 'How are you'];

// Using map + flat
const words1 = sentences.map(s => s.split(' ')).flat();
console.log(words1);  // ['Hello', 'world', 'How', 'are', 'you']

// Using flatMap
const words2 = sentences.flatMap(s => s.split(' '));
console.log(words2);  // ['Hello', 'world', 'How', 'are', 'you']

// Filtering and mapping in one go
const numbers = [1, 2, 3, 4];
const result = numbers.flatMap(n => n % 2 === 0 ? [n, n * 2] : []);
console.log(result);  // [2, 4, 4, 8]

forEach() #

Executes a function for each array element. Unlike map(), it doesn’t return a new array.

const fruits = ['apple', 'banana', 'orange'];

fruits.forEach((fruit, index) => {
  console.log(`${index + 1}. ${fruit}`);
});
// Output:
// 1. apple
// 2. banana
// 3. orange

// Note: You cannot break out of forEach
// Use a regular for loop if you need to break early

Array.from() #

Creates a new array from an array-like or iterable object.

// From string
const chars = Array.from('Hello');
console.log(chars);  // ['H', 'e', 'l', 'l', 'o']

// From Set
const uniqueNumbers = Array.from(new Set([1, 2, 2, 3, 3, 3]));
console.log(uniqueNumbers);  // [1, 2, 3]

// With mapping function
const doubled = Array.from([1, 2, 3], x => x * 2);
console.log(doubled);  // [2, 4, 6]

// Creating range
const range = Array.from({ length: 5 }, (_, i) => i + 1);
console.log(range);  // [1, 2, 3, 4, 5]

Array.of() #

Creates an array from arguments.

const arr1 = Array.of(7);        // [7]
const arr2 = Array.of(1, 2, 3);  // [1, 2, 3]

// Compare with Array constructor
const arr3 = Array(7);           // [empty × 7]
const arr4 = Array(1, 2, 3);     // [1, 2, 3]

Best Practices and Performance Tips #

1. Choose the Right Method #

Always consider whether you need to modify the original array or create a new one:

  • Mutating methods: push(), pop(), shift(), unshift(), splice(), sort(), reverse()
  • Non-mutating methods: map(), filter(), slice(), concat(), reduce()
// Bad: Unnecessarily creating copies
let numbers = [1, 2, 3];
numbers = numbers.concat([4]);  // Creates new array

// Good: Mutate when appropriate
numbers.push(4);  // Modifies existing array

2. Use Functional Approaches #

Prefer map(), filter(), and reduce() for cleaner, more maintainable code:

// Less readable
const result = [];
for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] % 2 === 0) {
    result.push(numbers[i] * 2);
  }
}

// More readable
const result = numbers
  .filter(n => n % 2 === 0)
  .map(n => n * 2);

3. Performance Considerations #

For large arrays, consider performance implications:

// For simple iterations, traditional loops are faster
const numbers = Array.from({ length: 1000000 }, (_, i) => i);

// Slower for large arrays
numbers.forEach(n => console.log(n));

// Faster for large arrays
for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}

4. Avoid Nested Loops #

Nested array methods can lead to O(n²) complexity:

// Bad: O(n²) complexity
const result = arr1.map(item1 => 
  arr2.filter(item2 => item2.id === item1.id)
);

// Better: Use a Map for O(n) complexity
const map = new Map(arr2.map(item => [item.id, item]));
const result = arr1.map(item1 => map.get(item1.id));

5. Use Modern Syntax #

Leverage modern JavaScript features for cleaner code:

// Old way
const copy = array.slice();

// Modern way
const copy = [...array];

// Removing duplicates
const unique = [...new Set(array)];

6. Chain Methods Wisely #

Method chaining is elegant but can impact performance:

// Multiple iterations
const result = numbers
  .filter(n => n > 0)
  .map(n => n * 2)
  .filter(n => n < 100);

// Single iteration (better for large arrays)
const result = numbers.reduce((acc, n) => {
  if (n > 0) {
    const doubled = n * 2;
    if (doubled < 100) {
      acc.push(doubled);
    }
  }
  return acc;
}, []);

7. Handle Edge Cases #

Always consider empty arrays and edge cases:

const numbers = [];

// Bad: May cause errors
const max = numbers.reduce((a, b) => Math.max(a, b));

// Good: Provide default value
const max = numbers.reduce((a, b) => Math.max(a, b), -Infinity);

// Or check length first
const max = numbers.length > 0 
  ? numbers.reduce((a, b) => Math.max(a, b))
  : null;

Conclusion #

JavaScript array methods are powerful tools that can make your code more readable, maintainable, and expressive. By understanding and using these methods effectively, you can write more elegant and efficient code. Remember to:

  • Choose the appropriate method for your use case
  • Consider performance implications when working with large datasets
  • Use functional programming approaches for better code readability
  • Handle edge cases and empty arrays appropriately
  • Stay updated with modern JavaScript features and syntax

Bookmark this cheatsheet and refer back to it whenever you need a quick refresher on JavaScript array methods. Happy coding!

Quick Reference Table #

MethodReturnsMutatesUse Case
push()New lengthYesAdd to end
pop()Removed elementYesRemove from end
unshift()New lengthYesAdd to start
shift()Removed elementYesRemove from start
map()New arrayNoTransform elements
filter()New arrayNoSelect elements
reduce()Single valueNoAggregate data
find()Element or undefinedNoFind single element
findIndex()Index or -1NoFind element index
some()BooleanNoTest any element
every()BooleanNoTest all elements
includes()BooleanNoCheck existence
slice()New arrayNoExtract portion
splice()Removed elementsYesModify in place
sort()Same arrayYesOrder elements
reverse()Same arrayYesReverse order
concat()New arrayNoCombine arrays
join()StringNoConvert to string
flat()New arrayNoFlatten nested arrays
flatMap()New arrayNoMap and flatten