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
- Quick Reference Table
- Array Creation
- Mutating Methods
- Non-Mutating Methods
- Iteration Methods
- Search & Filter Methods
- Transformation Methods
- Reduction Methods
- Array Inspection
- Array Conversion
- Array Destructuring
- Best Practices
- Common Pitfalls
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
| Method | Mutates | Returns | Description |
|---|---|---|---|
push() | ✅ | length | Add to end |
pop() | ✅ | element | Remove from end |
shift() | ✅ | element | Remove from start |
unshift() | ✅ | length | Add to start |
splice() | ✅ | array | Insert/remove/replace |
sort() | ✅ | array | Sort array |
reverse() | ✅ | array | Reverse order |
fill() | ✅ | array | Fill with value |
copyWithin() | ✅ | array | Copy within array |
concat() | ❌ | array | Combine arrays |
slice() | ❌ | array | Extract portion |
join() | ❌ | string | Join to string |
map() | ❌ | array | Transform elements |
filter() | ❌ | array | Filter elements |
reduce() | ❌ | value | Reduce to value |
reduceRight() | ❌ | value | Reduce right-to-left |
forEach() | ❌ | undefined | Iterate elements |
find() | ❌ | element | Find first match |
findIndex() | ❌ | number | Find first index |
some() | ❌ | boolean | Test if any pass |
every() | ❌ | boolean | Test if all pass |
includes() | ❌ | boolean | Check if includes |
indexOf() | ❌ | number | Find first index |
lastIndexOf() | ❌ | number | Find last index |
flat() | ❌ | array | Flatten array |
flatMap() | ❌ | array | Map then flatten |
Array Creation
Basic Creation 🔧
// Literal syntaxconst arr1 = [1, 2, 3];const arr2 = ["a", "b", "c"];const arr3 = []; // Empty array
// Array constructorconst arr4 = new Array(1, 2, 3); // [1, 2, 3]const arr5 = new Array(5); // Creates array with length 5 (sparse)// → [empty × 5]
// Array.of() - ES6const arr6 = Array.of(1, 2, 3); // [1, 2, 3]const arr7 = Array.of(5); // [5] (not sparse!)
// Array.from() - ES6const 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 valuesconst repeated = Array(5).fill(0); // [0, 0, 0, 0, 0]const range = Array.from({ length: 10 }, (_, i) => i + 1); // [1..10]
// Create array from argumentsfunction createArray(...args) { return Array.from(args); // Convert arguments to array}
// Create array from iterableconst 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 lengtharr.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 lengtharr.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 indexarr.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 elementconst last = arr.pop(); // → 5// arr is now [1, 2, 3, 4]
// shift() - Remove from beginning, returns removed elementconst first = arr.shift(); // → 1// arr is now [2, 3, 4]
// splice() - Remove/Replace elementsarr.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 orderarr.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 functionconst 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 objectsconst users = [ { name: "John", age: 30 }, { name: "Jane", age: 25 }, { name: "Bob", age: 35 },];users.sort((a, b) => a.age - b.age); // Sort by ageFilling Arrays 🎨
// fill() - Fill array with valueconst 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 arrayconst 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 arraysconst combined = arr1.concat(arr2); // [1, 2, 3, 4, 5, 6]// arr1 and arr2 unchanged
// Spread operator (ES6) - Modern alternativeconst 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 endarr.slice(2, 4); // [2, 3] - from index 2 to 4 (exclusive)arr.slice(-2); // [4, 5] - last 2 elementsarr.slice(1, -1); // [1, 2, 3, 4] - exclude first and lastarr.slice(); // [0, 1, 2, 3, 4, 5] - shallow copy
// Shallow copy patternconst copy = arr.slice(); // or [...arr]Joining 🔨
const arr = ["Hello", "World", "JavaScript"];
// join() - Convert to stringarr.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 elementarr.forEach((item, index) => { console.log(`Index ${index}: ${item}`);});// → Index 0: 1// → Index 1: 2// → etc.
// forEach() with thisArgconst 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 indexfor (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); // trueconst 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); // 2const firstNegative = arr.find((n) => n < 0); // undefined
// findIndex() - Find index of first match (short-circuits)const evenIndex = arr.findIndex((n) => n % 2 === 0); // 1const negativeIndex = arr.findIndex((n) => n < 0); // -1Search & Filter Methods
Finding Elements 🔍
const arr = [1, 2, 3, 2, 4, 2];
// indexOf() - Find first index of valuearr.indexOf(2); // 1arr.indexOf(5); // -1 (not found)arr.indexOf(2, 2); // 3 (start search from index 2)
// lastIndexOf() - Find last index of valuearr.lastIndexOf(2); // 5arr.lastIndexOf(2, 3); // 3 (search backwards from index 3)
// includes() - Check if value exists (ES2016)arr.includes(2); // truearr.includes(5); // falsearr.includes(2, 3); // true (start from index 3)
// find() - Find first element matching conditionconst 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 elementsconst 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 objectsconst 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 indexconst 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 elementconst doubled = numbers.map((n) => n * 2); // [2, 4, 6, 8, 10]const squared = numbers.map((n) => n ** 2); // [1, 4, 9, 16, 25]
// Map objectsconst 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 indexconst indexed = numbers.map((n, i) => `${i}: ${n}`); // ['0: 1', '1: 2', '2: 3', '3: 4', '4: 5']
// Transform and filter combinationconst 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 slotsconst 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 valueconst sum = numbers.reduce((acc, curr) => acc + curr, 0); // 15const product = numbers.reduce((acc, curr) => acc * curr, 1); // 120const max = numbers.reduce((acc, curr) => Math.max(acc, curr)); // 5
// reduce() with initial valueconst sumWithInit = numbers.reduce((acc, curr) => acc + curr, 10); // 25
// reduce() with indexconst 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 objectconst 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 leftconst rightSum = numbers.reduceRight((acc, curr) => acc + curr, 0); // 15const reverse = numbers.reduceRight((acc, curr) => { acc.push(curr); return acc;}, []); // [5, 4, 3, 2, 1]
// Useful for nested operationsconst 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 lengtharr.length; // 5
// Bracket notationarr[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 lengtharr.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 arrayArray.isArray(arr); // trueArray.isArray([]); // trueArray.isArray({}); // falseArray.isArray("array"); // falseArray.isArray(null); // false
// instanceofarr instanceof Array; // true
// Constructor checkarr.constructor === Array; // trueTesting Conditions ✅
const numbers = [2, 4, 6, 8];
// some() - At least one passesnumbers.some((n) => n > 5); // truenumbers.some((n) => n % 2 !== 0); // false
// every() - All passnumbers.every((n) => n % 2 === 0); // truenumbers.every((n) => n > 5); // false
// includes() - Value existsnumbers.includes(4); // truenumbers.includes(5); // falseArray Conversion
String Conversion 🔄
const arr = [1, 2, 3];
// toString() - Convert to stringarr.toString(); // '1,2,3'
// toLocaleString() - Locale-specific stringconst date = [new Date()];date.toLocaleString(); // '12/25/2023, 10:30:00 AM' (locale-dependent)
// join() - Custom separatorarr.join("-"); // '1-2-3'arr.join(""); // '123'Iterator Methods 🔄
const arr = ["a", "b", "c"];
// entries() - Key-value pairsfor (const [index, value] of arr.entries()) { console.log(index, value);}// → 0 'a'// → 1 'b'// → 2 'c'
// keys() - Indicesfor (const index of arr.keys()) { console.log(index);}// → 0// → 1// → 2
// values() - Valuesfor (const value of arr.values()) { console.log(value);}// → 'a'// → 'b'// → 'c'Array Destructuring
Basic Destructuring 🎁
const arr = [1, 2, 3, 4, 5];
// Basic destructuringconst [first, second] = arr; // first = 1, second = 2
// Skip elementsconst [a, , c] = arr; // a = 1, c = 3
// Rest operatorconst [head, ...tail] = arr; // head = 1, tail = [2, 3, 4, 5]
// Default valuesconst [x = 10, y = 20] = [1]; // x = 1, y = 20
// Swap variableslet a = 1, b = 2;[a, b] = [b, a]; // a = 2, b = 1Advanced Destructuring 🎯
// Nested destructuringconst nested = [1, [2, 3], 4];const [first, [second, third], fourth] = nested; // first=1, second=2, third=3, fourth=4
// Function parametersfunction process([first, second, ...rest]) { return { first, second, rest };}process([1, 2, 3, 4]); // { first: 1, second: 2, rest: [3, 4] }
// Return valuesfunction getCoords() { return [10, 20];}const [x, y] = getCoords(); // x = 10, y = 20
// Ignore restconst [first, , third] = [1, 2, 3, 4, 5]; // first=1, third=3Best Practices
✅ Do’s
// ✅ Use non-mutating methods when possibleconst 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 readabilityconst result = numbers .filter((n) => n > 0) .map((n) => n * 2) .reduce((sum, n) => sum + n, 0);
// ✅ Use Array.isArray() for type checkingif (Array.isArray(value)) { // Process array}
// ✅ Use destructuring for multiple assignmentsconst [first, second] = getValues();
// ✅ Use includes() instead of indexOf() !== -1if (arr.includes(value)) { // ✅ Clearer // ...}// Instead of: if (arr.indexOf(value) !== -1)
// ✅ Use map() when transforming, filter() when selectingconst doubled = numbers.map((n) => n * 2); // Transformconst evens = numbers.filter((n) => n % 2 === 0); // Select
// ✅ Use find() instead of filter()[0] when finding one itemconst 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 callbacksconst 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 iterationarr.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 arrayconst arr1 = [1, 2, 3];const arr2 = arr1;arr2.push(4);console.log(arr1); // [1, 2, 3, 4] - arr1 also changed!
// ✅ Solution: Create copy firstconst arr3 = [1, 2, 3];const arr4 = [...arr3]; // or arr3.slice()arr4.push(4);console.log(arr3); // [1, 2, 3] - unchangedSparse Arrays ⚠️
// ⚠️ Array constructor with single number creates sparse arrayconst sparse = new Array(5); // [empty × 5]sparse.length; // 5sparse[0]; // undefined0 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' bindingconst 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 bindconst 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/undefinedconst empty = [1, 2, 3].filter((n) => n > 10); // []if (empty) { // ✅ [] is truthy console.log("Has items"); // This runs!}
// ✅ Solution: Check lengthif (empty.length > 0) { console.log("Has items");}Performance Considerations ⚠️
// ⚠️ Chaining creates intermediate arraysconst 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 possibleconst result2 = largeArray.reduce((acc, n) => { if (n > 0) { const doubled = n * 2; if (doubled < 100) acc.push(doubled); } return acc;}, []);