JavaScript Array Methods: The Complete Cheat Sheet
JavaScript arrays come with dozens of built-in methods that make data manipulation concise and expressive. Whether you are filtering, transforming, searching, or sorting data, there is a method for it. This comprehensive cheat sheet covers every commonly used array method with clear examples, return values, and use cases so you can write cleaner, more efficient JavaScript.
Creating Arrays
Before diving into methods, here are the common ways to create arrays in JavaScript:
// Array literal (most common)
const fruits = ["apple", "banana", "cherry"];
// Array constructor
const empty = new Array(3); // [empty x 3]
const filled = new Array(1, 2, 3); // [1, 2, 3]
// Array.from โ convert iterables and array-like objects
const chars = Array.from("hello"); // ["h", "e", "l", "l", "o"]
const range = Array.from({ length: 5 }, (_, i) => i); // [0, 1, 2, 3, 4]
// Array.of โ create from arguments (no special behavior for single number)
const single = Array.of(3); // [3] โ not [empty x 3]
// Spread operator
const copy = [...fruits];
const merged = [...fruits, ...["date", "elderberry"]];Transformation Methods (Return New Array)
These methods create and return a new array without modifying the original. They are the foundation of functional programming patterns in JavaScript.
map() - Transform Every Element
Creates a new array by applying a function to each element. The original array is not modified.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
// [2, 4, 6, 8, 10]
const users = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 },
];
const names = users.map(user => user.name);
// ["Alice", "Bob"]
// With index parameter
const indexed = numbers.map((n, i) => `${i}: ${n}`);
// ["0: 1", "1: 2", "2: 3", "3: 4", "4: 5"]filter() - Select Matching Elements
Creates a new array with only the elements that pass a test function. Elements where the callback returns true are included.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evens = numbers.filter(n => n % 2 === 0);
// [2, 4, 6, 8, 10]
const adults = users.filter(user => user.age >= 18);
// Remove falsy values
const mixed = [0, "hello", "", null, 42, undefined, "world"];
const truthy = mixed.filter(Boolean);
// ["hello", 42, "world"]
// Remove duplicates (simple values)
const unique = numbers.filter((v, i, arr) => arr.indexOf(v) === i);reduce() - Accumulate into Single Value
Reduces an array to a single value by applying a function against an accumulator and each element. This is the most versatile array method.
const numbers = [1, 2, 3, 4, 5];
// Sum
const sum = numbers.reduce((acc, n) => acc + n, 0);
// 15
// Max value
const max = numbers.reduce((a, b) => Math.max(a, b));
// 5
// Group by property
const people = [
{ name: "Alice", dept: "Engineering" },
{ name: "Bob", dept: "Marketing" },
{ name: "Carol", dept: "Engineering" },
];
const grouped = people.reduce((acc, person) => {
const key = person.dept;
acc[key] = acc[key] || [];
acc[key].push(person);
return acc;
}, {} as Record<string, typeof people>);
// { Engineering: [...], Marketing: [...] }
// Count occurrences
const words = ["apple", "banana", "apple", "cherry", "banana", "apple"];
const counts = words.reduce((acc, word) => {
acc[word] = (acc[word] || 0) + 1;
return acc;
}, {} as Record<string, number>);
// { apple: 3, banana: 2, cherry: 1 }
// Flatten nested arrays (prefer flat() for simple cases)
const nested = [[1, 2], [3, 4], [5, 6]];
const flat = nested.reduce((acc, arr) => [...acc, ...arr], [] as number[]);
// [1, 2, 3, 4, 5, 6]flatMap() - Map Then Flatten
Combines map() and flat(1) in a single step. Useful when your mapping function returns arrays that should be flattened into the result.
const sentences = ["Hello world", "How are you"];
const words = sentences.flatMap(s => s.split(" "));
// ["Hello", "world", "How", "are", "you"]
// Filter and transform in one step
const nums = [1, 2, 3, 4, 5];
const evenDoubled = nums.flatMap(n => n % 2 === 0 ? [n * 2] : []);
// [4, 8]flat() - Flatten Nested Arrays
const nested = [1, [2, 3], [4, [5, 6]]];
nested.flat(); // [1, 2, 3, 4, [5, 6]] โ depth 1
nested.flat(2); // [1, 2, 3, 4, 5, 6] โ depth 2
nested.flat(Infinity); // flattens all levelsslice() - Extract a Portion
const arr = [1, 2, 3, 4, 5];
arr.slice(1, 3); // [2, 3] โ from index 1 to 3 (exclusive)
arr.slice(2); // [3, 4, 5] โ from index 2 to end
arr.slice(-2); // [4, 5] โ last 2 elements
arr.slice(); // [1, 2, 3, 4, 5] โ shallow copyconcat() - Merge Arrays
const a = [1, 2];
const b = [3, 4];
const c = [5, 6];
a.concat(b); // [1, 2, 3, 4]
a.concat(b, c); // [1, 2, 3, 4, 5, 6]
[...a, ...b, ...c]; // [1, 2, 3, 4, 5, 6] โ spread alternativeSearching Methods
These methods help you find elements or check whether certain conditions are met within an array.
find() and findIndex()
const users = [
{ id: 1, name: "Alice", role: "admin" },
{ id: 2, name: "Bob", role: "user" },
{ id: 3, name: "Carol", role: "user" },
];
// find โ returns first matching element or undefined
const admin = users.find(u => u.role === "admin");
// { id: 1, name: "Alice", role: "admin" }
// findIndex โ returns index of first match or -1
const index = users.findIndex(u => u.name === "Bob");
// 1
// findLast and findLastIndex (ES2023)
const lastUser = users.findLast(u => u.role === "user");
// { id: 3, name: "Carol", role: "user" }includes(), indexOf(), lastIndexOf()
const fruits = ["apple", "banana", "cherry", "banana"];
fruits.includes("banana"); // true
fruits.includes("grape"); // false
fruits.indexOf("banana"); // 1 (first occurrence)
fruits.lastIndexOf("banana"); // 3 (last occurrence)
fruits.indexOf("grape"); // -1 (not found)some() and every()
const numbers = [1, 2, 3, 4, 5];
// some โ at least one passes the test
numbers.some(n => n > 4); // true
numbers.some(n => n > 10); // false
// every โ all must pass the test
numbers.every(n => n > 0); // true
numbers.every(n => n > 3); // false
// Practical: validate form fields
const fields = [
{ name: "email", value: "test@test.com", valid: true },
{ name: "name", value: "", valid: false },
];
const allValid = fields.every(f => f.valid); // falseMutation Methods (Modify Original Array)
These methods change the original array in place. Use them when you intentionally want to modify the existing array rather than create a new one.
push(), pop(), unshift(), shift()
const arr = [1, 2, 3];
// Add to end โ returns new length
arr.push(4); // arr = [1, 2, 3, 4], returns 4
arr.push(5, 6); // arr = [1, 2, 3, 4, 5, 6], returns 6
// Remove from end โ returns removed element
arr.pop(); // arr = [1, 2, 3, 4, 5], returns 6
// Add to beginning โ returns new length
arr.unshift(0); // arr = [0, 1, 2, 3, 4, 5], returns 6
// Remove from beginning โ returns removed element
arr.shift(); // arr = [1, 2, 3, 4, 5], returns 0splice() - Add, Remove, or Replace
const arr = [1, 2, 3, 4, 5];
// Remove 2 elements starting at index 1
arr.splice(1, 2); // returns [2, 3], arr = [1, 4, 5]
// Insert at index 1 without removing
arr.splice(1, 0, 2, 3); // arr = [1, 2, 3, 4, 5]
// Replace 1 element at index 2
arr.splice(2, 1, 99); // returns [3], arr = [1, 2, 99, 4, 5]sort() and reverse()
// sort modifies in place โ returns the same array
const nums = [3, 1, 4, 1, 5, 9, 2, 6];
// Default sort converts to strings (careful with numbers!)
nums.sort(); // [1, 1, 2, 3, 4, 5, 6, 9]
// Numeric sort
nums.sort((a, b) => a - b); // ascending
nums.sort((a, b) => b - a); // descending
// Sort objects by property
const users = [
{ name: "Charlie", age: 35 },
{ name: "Alice", age: 28 },
{ name: "Bob", age: 32 },
];
users.sort((a, b) => a.age - b.age);
// Sorted by age ascending
// reverse โ reverses in place
const arr = [1, 2, 3];
arr.reverse(); // [3, 2, 1]
// Non-mutating alternatives (ES2023)
const sorted = nums.toSorted((a, b) => a - b);
const reversed = arr.toReversed();
const spliced = arr.toSpliced(1, 1, 99);fill() and copyWithin()
// fill โ fill with a value
const arr = new Array(5).fill(0); // [0, 0, 0, 0, 0]
arr.fill(7, 2, 4); // [0, 0, 7, 7, 0]
// copyWithin โ copy part of array to another location
const arr2 = [1, 2, 3, 4, 5];
arr2.copyWithin(0, 3); // [4, 5, 3, 4, 5] โ copy from index 3 to index 0Iteration Methods
const fruits = ["apple", "banana", "cherry"];
// forEach โ execute for each element (returns undefined)
fruits.forEach((fruit, index) => {
console.log(`${index}: ${fruit}`);
});
// for...of โ modern loop with break/continue support
for (const fruit of fruits) {
if (fruit === "banana") continue;
console.log(fruit);
}
// entries(), keys(), values()
for (const [index, fruit] of fruits.entries()) {
console.log(`${index}: ${fruit}`);
}
for (const key of fruits.keys()) {
console.log(key); // 0, 1, 2
}
for (const value of fruits.values()) {
console.log(value); // "apple", "banana", "cherry"
}Conversion Methods
const arr = [1, 2, 3, 4, 5];
// join โ convert to string with separator
arr.join(", "); // "1, 2, 3, 4, 5"
arr.join("-"); // "1-2-3-4-5"
arr.join(""); // "12345"
// toString
arr.toString(); // "1,2,3,4,5"
// Array.isArray โ check if value is an array
Array.isArray([1, 2, 3]); // true
Array.isArray("hello"); // false
Array.isArray({ length: 3 }); // falseES2023+ New Array Methods
Recent JavaScript versions added several non-mutating alternatives to existing mutation methods. These return new arrays instead of modifying the original.
const original = [3, 1, 4, 1, 5];
// toSorted โ non-mutating sort
const sorted = original.toSorted((a, b) => a - b);
// sorted = [1, 1, 3, 4, 5], original unchanged
// toReversed โ non-mutating reverse
const reversed = original.toReversed();
// reversed = [5, 1, 4, 1, 3], original unchanged
// toSpliced โ non-mutating splice
const spliced = original.toSpliced(1, 2, 9, 8);
// spliced = [3, 9, 8, 1, 5], original unchanged
// with โ non-mutating index assignment
const updated = original.with(2, 99);
// updated = [3, 1, 99, 1, 5], original unchanged
// Object.groupBy (ES2024) โ group by callback result
const items = [
{ name: "Apple", type: "fruit" },
{ name: "Carrot", type: "vegetable" },
{ name: "Banana", type: "fruit" },
];
const groups = Object.groupBy(items, item => item.type);
// { fruit: [{...}, {...}], vegetable: [{...}] }Quick Reference Table
| Method | Returns | Mutates? | Use Case |
|---|---|---|---|
map() | New array | No | Transform each element |
filter() | New array | No | Select matching elements |
reduce() | Any value | No | Accumulate to single value |
find() | Element or undefined | No | First match |
findIndex() | Number | No | Index of first match |
some() | Boolean | No | At least one passes |
every() | Boolean | No | All pass |
includes() | Boolean | No | Contains value |
flat() | New array | No | Flatten nested arrays |
flatMap() | New array | No | Map then flatten |
slice() | New array | No | Extract portion |
concat() | New array | No | Merge arrays |
sort() | Same array | Yes | Sort in place |
reverse() | Same array | Yes | Reverse in place |
push() | New length | Yes | Add to end |
pop() | Removed element | Yes | Remove from end |
splice() | Removed elements | Yes | Add/remove/replace |
forEach() | undefined | No | Side effects loop |
Frequently Asked Questions
What is the difference between map() and forEach()?
map() returns a new array with the transformed values, while forEach() returnsundefined and is used only for side effects like logging or DOM manipulation. If you need the result, use map(). If you just need to do something with each element, use forEach().
When should I use reduce() vs a for loop?
Use reduce() when the operation naturally accumulates into a single value (sum, grouping, counting). Use a for loop when the logic is complex, involves multiple accumulators, or needs early termination. Readability should be the deciding factor.
How do I remove duplicates from an array?
For primitive values, use [...new Set(array)]. For objects, use filter() with aSet tracking seen keys, or use reduce() to build a map and extract values.
What is the performance of find() vs filter()?
find() stops at the first match and returns immediately, making it O(1) in the best case.filter() always iterates through the entire array. When you only need one result, always prefer find().
Are toSorted() and toReversed() supported in all browsers?
These ES2023 methods are supported in Chrome 110+, Firefox 115+, Safari 16+, and Node.js 20+. For older environments, use [...arr].sort() and [...arr].reverse() as non-mutating alternatives.