Skip to main content

JavaScript Array Methods Cheatsheet

Comprehensive quick reference for JavaScript array methods, including mutating, non-mutating, iteration, and transformation operations. Essential guide for ES6+ array manipulation.

Table of Contents


Prerequisites

JavaScript Version: This cheatsheet targets ES6+ (ES2015+). Some methods require specific versions (noted inline).

// Modern JavaScript features used
// ES6+: Arrow functions, const/let, spread operator, destructuring
// ES2017+: Array.includes()
// ES2019+: Array.flat(), Array.flatMap()
// ES2022+: Array.at()

Browser Support: Most methods work in all modern browsers. Check MDN compatibility for specific versions.


Quick Reference Table

MethodMutatesReturnsDescription
push()lengthAdd to end
pop()elementRemove from end
shift()elementRemove from start
unshift()lengthAdd to start
splice()arrayInsert/remove/replace
sort()arraySort array
reverse()arrayReverse order
fill()arrayFill with value
copyWithin()arrayCopy within array
concat()arrayCombine arrays
slice()arrayExtract portion
join()stringJoin to string
map()arrayTransform elements
filter()arrayFilter elements
reduce()valueReduce to value
reduceRight()valueReduce right-to-left
forEach()undefinedIterate elements
find()elementFind first match
findIndex()numberFind first index
some()booleanTest if any pass
every()booleanTest if all pass
includes()booleanCheck if includes
indexOf()numberFind first index
lastIndexOf()numberFind last index
flat()arrayFlatten array
flatMap()arrayMap then flatten

Array Creation

Basic Creation 🔧

// Literal syntax
const arr1 = [1, 2, 3];
const arr2 = ["a", "b", "c"];
const arr3 = []; // Empty array
// Array constructor
const arr4 = new Array(1, 2, 3); // [1, 2, 3]
const arr5 = new Array(5); // Creates array with length 5 (sparse)
// → [empty × 5]
// Array.of() - ES6
const arr6 = Array.of(1, 2, 3); // [1, 2, 3]
const arr7 = Array.of(5); // [5] (not sparse!)
// Array.from() - ES6
const arr8 = Array.from("hello"); // ['h', 'e', 'l', 'l', 'o']
const arr9 = Array.from([1, 2, 3], (x) => x * 2); // [2, 4, 6]
const arr10 = Array.from({ length: 5 }, (_, i) => i); // [0, 1, 2, 3, 4]

Special Patterns 🎯

// Create array with repeated values
const repeated = Array(5).fill(0); // [0, 0, 0, 0, 0]
const range = Array.from({ length: 10 }, (_, i) => i + 1); // [1..10]
// Create array from arguments
function createArray(...args) {
return Array.from(args); // Convert arguments to array
}
// Create array from iterable
const set = new Set([1, 2, 3]);
const arrFromSet = Array.from(set); // [1, 2, 3]

Mutating Methods

⚠️ Warning: Mutating methods modify the original array. Use with caution when you need to preserve the original array.

Adding Elements ➕

const arr = [1, 2, 3];
// push() - Add to end, returns new length
arr.push(4); // → 4 (length)
// arr is now [1, 2, 3, 4]
arr.push(5, 6); // Add multiple
// arr is now [1, 2, 3, 4, 5, 6]
// unshift() - Add to beginning, returns new length
arr.unshift(0); // → 7 (length)
// arr is now [0, 1, 2, 3, 4, 5, 6]
arr.unshift(-2, -1); // Add multiple
// arr is now [-2, -1, 0, 1, 2, 3, 4, 5, 6]
// splice() - Insert at index
arr.splice(2, 0, "inserted"); // Insert at index 2, delete 0 items
// arr is now [-2, -1, 'inserted', 0, 1, 2, 3, 4, 5, 6]

Removing Elements ➖

const arr = [1, 2, 3, 4, 5];
// pop() - Remove from end, returns removed element
const last = arr.pop(); // → 5
// arr is now [1, 2, 3, 4]
// shift() - Remove from beginning, returns removed element
const first = arr.shift(); // → 1
// arr is now [2, 3, 4]
// splice() - Remove/Replace elements
arr.splice(1, 1); // Remove 1 element at index 1
// arr is now [2, 4]
arr.splice(0, 1, "replaced"); // Replace 1 element at index 0
// arr is now ['replaced', 4]

Reordering Elements 🔄

const arr = [3, 1, 4, 1, 5];
// reverse() - Reverse array order
arr.reverse(); // → [5, 1, 4, 1, 3]
// arr is now [5, 1, 4, 1, 3]
// sort() - Sort array (modifies original)
arr.sort(); // Default: converts to strings and sorts
// → [1, 1, 3, 4, 5]
// sort() with compare function
const numbers = [10, 5, 40, 25, 1000];
numbers.sort((a, b) => a - b); // Ascending
// → [5, 10, 25, 40, 1000]
numbers.sort((a, b) => b - a); // Descending
// → [1000, 40, 25, 10, 5]
// Sort objects
const users = [
{ name: "John", age: 30 },
{ name: "Jane", age: 25 },
{ name: "Bob", age: 35 },
];
users.sort((a, b) => a.age - b.age); // Sort by age

Filling Arrays 🎨

// fill() - Fill array with value
const arr = new Array(5).fill(0); // [0, 0, 0, 0, 0]
arr.fill(1, 2, 4); // Fill with 1 from index 2 to 4 (exclusive)
// → [0, 0, 1, 1, 0]
// copyWithin() - Copy elements within array
const arr2 = [1, 2, 3, 4, 5];
arr2.copyWithin(0, 3); // Copy elements from index 3 to start
// → [4, 5, 3, 4, 5]
arr2.copyWithin(1, 0, 2); // Copy first 2 elements to index 1
// → [4, 4, 5, 4, 5]

Non-Mutating Methods

Best Practice: Prefer non-mutating methods when you need to preserve the original array.

Concatenation 🔗

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
// concat() - Combine arrays
const combined = arr1.concat(arr2); // [1, 2, 3, 4, 5, 6]
// arr1 and arr2 unchanged
// Spread operator (ES6) - Modern alternative
const combined2 = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
const withExtra = [...arr1, 7, 8, ...arr2]; // [1, 2, 3, 7, 8, 4, 5, 6]

Slicing ✂️

const arr = [0, 1, 2, 3, 4, 5];
// slice() - Extract portion (start, end)
arr.slice(2); // [2, 3, 4, 5] - from index 2 to end
arr.slice(2, 4); // [2, 3] - from index 2 to 4 (exclusive)
arr.slice(-2); // [4, 5] - last 2 elements
arr.slice(1, -1); // [1, 2, 3, 4] - exclude first and last
arr.slice(); // [0, 1, 2, 3, 4, 5] - shallow copy
// Shallow copy pattern
const copy = arr.slice(); // or [...arr]

Joining 🔨

const arr = ["Hello", "World", "JavaScript"];
// join() - Convert to string
arr.join(); // 'Hello,World,JavaScript' (default separator: comma)
arr.join(" "); // 'Hello World JavaScript'
arr.join("-"); // 'Hello-World-JavaScript'
arr.join(""); // 'HelloWorldJavaScript'

Iteration Methods

Basic Iteration 🔁

const arr = [1, 2, 3, 4, 5];
// forEach() - Execute function for each element
arr.forEach((item, index) => {
console.log(`Index ${index}: ${item}`);
});
// → Index 0: 1
// → Index 1: 2
// → etc.
// forEach() with thisArg
const obj = { multiplier: 2 };
arr.forEach(function (item) {
console.log(item * this.multiplier);
}, obj); // 'this' refers to obj
// for...of loop (ES6)
for (const item of arr) {
console.log(item);
}
// for...of with index
for (const [index, item] of arr.entries()) {
console.log(index, item);
}

Early Termination ⏹️

const arr = [1, 2, 3, 4, 5];
// some() - Test if ANY element passes (short-circuits)
const hasEven = arr.some((n) => n % 2 === 0); // true (stops at 2)
const hasNegative = arr.some((n) => n < 0); // false
// every() - Test if ALL elements pass (short-circuits)
const allPositive = arr.every((n) => n > 0); // true
const allEven = arr.every((n) => n % 2 === 0); // false (stops at 1)
// find() - Find first matching element (short-circuits)
const firstEven = arr.find((n) => n % 2 === 0); // 2
const firstNegative = arr.find((n) => n < 0); // undefined
// findIndex() - Find index of first match (short-circuits)
const evenIndex = arr.findIndex((n) => n % 2 === 0); // 1
const negativeIndex = arr.findIndex((n) => n < 0); // -1

Search & Filter Methods

Finding Elements 🔍

const arr = [1, 2, 3, 2, 4, 2];
// indexOf() - Find first index of value
arr.indexOf(2); // 1
arr.indexOf(5); // -1 (not found)
arr.indexOf(2, 2); // 3 (start search from index 2)
// lastIndexOf() - Find last index of value
arr.lastIndexOf(2); // 5
arr.lastIndexOf(2, 3); // 3 (search backwards from index 3)
// includes() - Check if value exists (ES2016)
arr.includes(2); // true
arr.includes(5); // false
arr.includes(2, 3); // true (start from index 3)
// find() - Find first element matching condition
const users = [
{ id: 1, name: "John", active: true },
{ id: 2, name: "Jane", active: false },
{ id: 3, name: "Bob", active: true },
];
const activeUser = users.find((user) => user.active); // { id: 1, name: 'John', active: true }
// findLast() - Find last element matching condition (ES2023)
const lastActive = users.findLast((user) => user.active); // { id: 3, name: 'Bob', active: true }

Filtering Elements 🎯

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// filter() - Create new array with matching elements
const evens = numbers.filter((n) => n % 2 === 0); // [2, 4, 6, 8, 10]
const odds = numbers.filter((n) => n % 2 !== 0); // [1, 3, 5, 7, 9]
const greaterThan5 = numbers.filter((n) => n > 5); // [6, 7, 8, 9, 10]
// Filter objects
const users = [
{ name: "John", age: 30 },
{ name: "Jane", age: 25 },
{ name: "Bob", age: 35 },
];
const adults = users.filter((user) => user.age >= 30); // [{ name: 'John', age: 30 }, { name: 'Bob', age: 35 }]
// Filter with index
const firstHalf = numbers.filter((n, index) => index < numbers.length / 2); // [1, 2, 3, 4, 5]

Transformation Methods

Mapping Elements 🗺️

const numbers = [1, 2, 3, 4, 5];
// map() - Transform each element
const doubled = numbers.map((n) => n * 2); // [2, 4, 6, 8, 10]
const squared = numbers.map((n) => n ** 2); // [1, 4, 9, 16, 25]
// Map objects
const users = [
{ name: "John", age: 30 },
{ name: "Jane", age: 25 },
];
const names = users.map((user) => user.name); // ['John', 'Jane']
const ages = users.map((user) => user.age); // [30, 25]
// Map with index
const indexed = numbers.map((n, i) => `${i}: ${n}`); // ['0: 1', '1: 2', '2: 3', '3: 4', '4: 5']
// Transform and filter combination
const doubledEvens = numbers.filter((n) => n % 2 === 0).map((n) => n * 2); // [4, 8]

Flattening Arrays 📦

const nested = [1, [2, 3], [4, [5, 6]]];
// flat() - Flatten array (ES2019)
nested.flat(); // [1, 2, 3, 4, [5, 6]] (default depth: 1)
nested.flat(2); // [1, 2, 3, 4, 5, 6] (depth: 2)
nested.flat(Infinity); // [1, 2, 3, 4, 5, 6] (fully flatten)
// flatMap() - Map then flatten one level (ES2019)
const arr = [1, 2, 3];
arr.flatMap((n) => [n, n * 2]); // [1, 2, 2, 4, 3, 6]
// Equivalent to: arr.map(n => [n, n * 2]).flat()
// Remove empty slots
const sparse = [1, , , 4];
sparse.flat(); // [1, 4] (removes empty slots)

Reduction Methods

Single Value Reduction 📊

const numbers = [1, 2, 3, 4, 5];
// reduce() - Reduce to single value
const sum = numbers.reduce((acc, curr) => acc + curr, 0); // 15
const product = numbers.reduce((acc, curr) => acc * curr, 1); // 120
const max = numbers.reduce((acc, curr) => Math.max(acc, curr)); // 5
// reduce() with initial value
const sumWithInit = numbers.reduce((acc, curr) => acc + curr, 10); // 25
// reduce() with index
const indexedSum = numbers.reduce((acc, curr, index) => {
return acc + curr * index;
}, 0); // 0 + 1*0 + 2*1 + 3*2 + 4*3 + 5*4 = 40
// Transform array to object
const users = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
];
const userMap = users.reduce((acc, user) => {
acc[user.id] = user.name;
return acc;
}, {}); // { 1: 'John', 2: 'Jane' }

Right-to-Left Reduction ⬅️

const numbers = [1, 2, 3, 4, 5];
// reduceRight() - Reduce from right to left
const rightSum = numbers.reduceRight((acc, curr) => acc + curr, 0); // 15
const reverse = numbers.reduceRight((acc, curr) => {
acc.push(curr);
return acc;
}, []); // [5, 4, 3, 2, 1]
// Useful for nested operations
const nested = [
[1, 2],
[3, 4],
[5, 6],
];
const flattened = nested.reduceRight((acc, curr) => acc.concat(curr), []); // [5, 6, 3, 4, 1, 2]

Array Inspection

Length & Access 📏

const arr = [1, 2, 3, 4, 5];
// length - Array length
arr.length; // 5
// Bracket notation
arr[0]; // 1 (first element)
arr[arr.length - 1]; // 5 (last element)
// at() - Relative indexing (ES2022)
arr.at(0); // 1 (first element)
arr.at(-1); // 5 (last element)
arr.at(-2); // 4 (second to last)
arr.at(10); // undefined (out of bounds)
// Modifying length
arr.length = 3; // Truncate array
// arr is now [1, 2, 3]
arr.length = 5; // Extend array (sparse)
// arr is now [1, 2, 3, empty × 2]

Type Checking 🔎

const arr = [1, 2, 3];
// Array.isArray() - Check if value is array
Array.isArray(arr); // true
Array.isArray([]); // true
Array.isArray({}); // false
Array.isArray("array"); // false
Array.isArray(null); // false
// instanceof
arr instanceof Array; // true
// Constructor check
arr.constructor === Array; // true

Testing Conditions ✅

const numbers = [2, 4, 6, 8];
// some() - At least one passes
numbers.some((n) => n > 5); // true
numbers.some((n) => n % 2 !== 0); // false
// every() - All pass
numbers.every((n) => n % 2 === 0); // true
numbers.every((n) => n > 5); // false
// includes() - Value exists
numbers.includes(4); // true
numbers.includes(5); // false

Array Conversion

String Conversion 🔄

const arr = [1, 2, 3];
// toString() - Convert to string
arr.toString(); // '1,2,3'
// toLocaleString() - Locale-specific string
const date = [new Date()];
date.toLocaleString(); // '12/25/2023, 10:30:00 AM' (locale-dependent)
// join() - Custom separator
arr.join("-"); // '1-2-3'
arr.join(""); // '123'

Iterator Methods 🔄

const arr = ["a", "b", "c"];
// entries() - Key-value pairs
for (const [index, value] of arr.entries()) {
console.log(index, value);
}
// → 0 'a'
// → 1 'b'
// → 2 'c'
// keys() - Indices
for (const index of arr.keys()) {
console.log(index);
}
// → 0
// → 1
// → 2
// values() - Values
for (const value of arr.values()) {
console.log(value);
}
// → 'a'
// → 'b'
// → 'c'

Array Destructuring

Basic Destructuring 🎁

const arr = [1, 2, 3, 4, 5];
// Basic destructuring
const [first, second] = arr; // first = 1, second = 2
// Skip elements
const [a, , c] = arr; // a = 1, c = 3
// Rest operator
const [head, ...tail] = arr; // head = 1, tail = [2, 3, 4, 5]
// Default values
const [x = 10, y = 20] = [1]; // x = 1, y = 20
// Swap variables
let a = 1,
b = 2;
[a, b] = [b, a]; // a = 2, b = 1

Advanced Destructuring 🎯

// Nested destructuring
const nested = [1, [2, 3], 4];
const [first, [second, third], fourth] = nested; // first=1, second=2, third=3, fourth=4
// Function parameters
function process([first, second, ...rest]) {
return { first, second, rest };
}
process([1, 2, 3, 4]); // { first: 1, second: 2, rest: [3, 4] }
// Return values
function getCoords() {
return [10, 20];
}
const [x, y] = getCoords(); // x = 10, y = 20
// Ignore rest
const [first, , third] = [1, 2, 3, 4, 5]; // first=1, third=3

Best Practices

✅ Do’s

// ✅ Use non-mutating methods when possible
const original = [1, 2, 3];
const doubled = original.map((n) => n * 2); // original unchanged
// ✅ Use const for arrays (array reference is constant)
const arr = [1, 2, 3];
arr.push(4); // ✅ OK - modifying contents
// arr = [5, 6]; // ❌ Error - reassigning reference
// ✅ Chain methods for readability
const result = numbers
.filter((n) => n > 0)
.map((n) => n * 2)
.reduce((sum, n) => sum + n, 0);
// ✅ Use Array.isArray() for type checking
if (Array.isArray(value)) {
// Process array
}
// ✅ Use destructuring for multiple assignments
const [first, second] = getValues();
// ✅ Use includes() instead of indexOf() !== -1
if (arr.includes(value)) {
// ✅ Clearer
// ...
}
// Instead of: if (arr.indexOf(value) !== -1)
// ✅ Use map() when transforming, filter() when selecting
const doubled = numbers.map((n) => n * 2); // Transform
const evens = numbers.filter((n) => n % 2 === 0); // Select
// ✅ Use find() instead of filter()[0] when finding one item
const user = users.find((u) => u.id === 1); // ✅ Stops at first match
// Instead of: users.filter(u => u.id === 1)[0] // Checks all

❌ Don’ts

// ❌ Don't mutate arrays in map/filter callbacks
const doubled = numbers.map((n) => {
numbers.push(n * 2); // ❌ Mutating original array
return n * 2;
});
// ❌ Don't use for...in for arrays (iterates over properties)
for (const index in arr) {
// ❌ May include non-index properties
console.log(arr[index]);
}
// Use: for (const item of arr) or arr.forEach()
// ❌ Don't use == for array comparison (compares references)
[1, 2, 3] == [1, 2, 3]; // false (different references)
// Use: JSON.stringify() or deep comparison library
// ❌ Don't modify array during iteration
arr.forEach((item, index) => {
arr.push(item * 2); // ❌ Can cause unexpected behavior
});
// ❌ Don't use delete on array elements (creates sparse array)
delete arr[1]; // ❌ Creates empty slot
// Use: arr.splice(1, 1) or arr.filter()
// ❌ Don't use var in loops (closure issues)
for (var i = 0; i < arr.length; i++) {
// ❌ 'i' leaks to outer scope
setTimeout(() => console.log(arr[i]), 100);
}
// Use: let or for...of
// ❌ Don't use sort() without compare function for numbers
[10, 5, 40, 25].sort(); // ❌ ['10', '25', '40', '5'] (string sort!)
// Use: [10, 5, 40, 25].sort((a, b) => a - b)

Common Pitfalls

Mutating vs Non-Mutating ⚠️

// ⚠️ Mutating methods modify original array
const arr1 = [1, 2, 3];
const arr2 = arr1;
arr2.push(4);
console.log(arr1); // [1, 2, 3, 4] - arr1 also changed!
// ✅ Solution: Create copy first
const arr3 = [1, 2, 3];
const arr4 = [...arr3]; // or arr3.slice()
arr4.push(4);
console.log(arr3); // [1, 2, 3] - unchanged

Sparse Arrays ⚠️

// ⚠️ Array constructor with single number creates sparse array
const sparse = new Array(5); // [empty × 5]
sparse.length; // 5
sparse[0]; // undefined
0 in sparse; // false (no element at index 0)
// ✅ Solution: Use Array.from() or fill()
const dense = Array.from({ length: 5 }, (_, i) => i); // [0, 1, 2, 3, 4]
const filled = Array(5).fill(0); // [0, 0, 0, 0, 0]

Callback Context ⚠️

// ⚠️ Arrow functions don't have 'this' binding
const obj = {
multiplier: 2,
numbers: [1, 2, 3],
double() {
this.numbers.forEach(function (n) {
console.log(n * this.multiplier); // ❌ 'this' is undefined
});
},
};
// ✅ Solution: Use arrow function or bind
const obj2 = {
multiplier: 2,
numbers: [1, 2, 3],
double() {
this.numbers.forEach((n) => {
console.log(n * this.multiplier); // ✅ 'this' refers to obj2
});
},
};

Empty Array Results ⚠️

// ⚠️ Methods return empty array, not null/undefined
const empty = [1, 2, 3].filter((n) => n > 10); // []
if (empty) {
// ✅ [] is truthy
console.log("Has items"); // This runs!
}
// ✅ Solution: Check length
if (empty.length > 0) {
console.log("Has items");
}

Performance Considerations ⚠️

// ⚠️ Chaining creates intermediate arrays
const result = largeArray
.filter((n) => n > 0) // Creates array 1
.map((n) => n * 2) // Creates array 2
.filter((n) => n < 100); // Creates array 3
// ✅ Solution: Combine operations when possible
const result2 = largeArray.reduce((acc, n) => {
if (n > 0) {
const doubled = n * 2;
if (doubled < 100) acc.push(doubled);
}
return acc;
}, []);