JavaScript arrays look simple until you need to transform API data, remove duplicates, sort records, flatten nested values, or avoid mutating state by accident. This cheat sheet is a practical reference for the array methods developers reach for most often, organized by task instead of alphabetically. You will get clear rules for choosing the right method, copy-paste examples you can adapt quickly, and a short list of mistakes worth avoiding in production code.
Overview
If you search for a JavaScript array methods cheat sheet, you usually get one of two extremes: a long documentation dump or a shallow beginner list. What is more useful in day-to-day work is a task-based reference. When you are cleaning API responses, building UI lists, validating form data, or reshaping values before storage, the real question is not “What methods exist?” but “Which method matches this job?”
Here is a simple mental model that covers most common work:
- Transform each item:
map() - Keep only matching items:
filter() - Find one item:
find()orfindIndex() - Check whether any or all match:
some()orevery() - Combine into one value:
reduce() - Reorder items:
sort(),reverse(),toSorted() - Add or remove items immutably:
concat(), spread syntax,slice(),toSpliced() - Flatten nested arrays:
flat()orflatMap() - Create subsets:
slice() - Test membership:
includes()
One more distinction matters a lot: some methods return a new array, while others mutate the original array. In modern frontend work, especially with state management, that difference is often more important than the method name itself.
Core framework
Use this framework when deciding which array method to reach for.
1. Ask whether you need a new array, one value, or a boolean
This one question removes a lot of confusion.
- New array:
map(),filter(),slice(),flat(),concat() - Single value:
find(),reduce(),at() - Boolean:
some(),every(),includes()
2. Prefer intent over cleverness
Many array methods can be forced to solve the same problem, but the clearest one is usually best. For example, use filter() to remove inactive users instead of using reduce() just because it can do everything.
3. Know which methods mutate
These common methods mutate the original array:
sort()reverse()splice()push(),pop(),shift(),unshift()fill()
These methods usually return a new value without changing the original:
map()filter()find()slice()concat()flat()toSorted(),toReversed(),toSpliced()
If you work in React or any environment where immutable updates make debugging easier, lean toward non-mutating methods by default.
4. Choose readable callback parameters
Most array callbacks accept up to three arguments:
array.method((item, index, originalArray) => {
// ...
})In practice, use only what you need. If you only need the item, keep it short. If you need the index for IDs, labels, or fallback ordering, add it deliberately.
5. Watch data shape before method choice
A lot of bugs happen because developers expect a flat array of objects but actually have nested arrays, nullable values, or mixed types. Before writing the method chain, verify the shape of the data. This is especially important when parsing CSV rows, paginated API results, or values pulled from local storage. Related reading: How to Parse CSV Files Safely: Edge Cases, Encoding, and Validation and Local Storage vs Session Storage vs Cookies: What to Use and When.
Practical examples
This section groups array methods by the jobs developers actually do.
Transform values with map()
Use map() when the output array should have the same number of items as the input array, but each item changes shape.
const users = [
{ id: 1, name: 'Ava', active: true },
{ id: 2, name: 'Leo', active: false }
];
const names = users.map(user => user.name);
// ['Ava', 'Leo']
const options = users.map(user => ({
label: user.name,
value: user.id
}));Good fit: UI dropdown options, API response cleanup, rendering labels, normalizing field names.
Remove items with filter()
Use filter() when you want fewer items in the result.
const activeUsers = users.filter(user => user.active);
// [{ id: 1, name: 'Ava', active: true }]This is one of the clearest methods in JavaScript. If your goal is “keep only the records that match,” filter() is probably the right answer.
Find one item with find() and findIndex()
Use find() when you want the first matching item, not a full list.
const user = users.find(user => user.id === 2);
// { id: 2, name: 'Leo', active: false }
const index = users.findIndex(user => user.id === 2);
// 1If you only need to know whether a match exists, use some() instead of find().
Test conditions with some() and every()
const hasInactiveUsers = users.some(user => !user.active);
// true
const allActive = users.every(user => user.active);
// falseThese methods are useful in form validation, permissions checks, and feature gating. If you are working on input validation flows, see Frontend Form Validation Guide: Native HTML, JavaScript, and UX Best Practices.
Combine values with reduce()
reduce() is powerful, but it is easiest to maintain when the accumulator has a clear purpose.
const prices = [19, 25, 30];
const total = prices.reduce((sum, price) => sum + price, 0);
// 74Grouping is another common use:
const orders = [
{ id: 1, status: 'paid' },
{ id: 2, status: 'pending' },
{ id: 3, status: 'paid' }
];
const grouped = orders.reduce((acc, order) => {
if (!acc[order.status]) acc[order.status] = [];
acc[order.status].push(order);
return acc;
}, {});
// {
// paid: [{...}, {...}],
// pending: [{...}]
// }If a reduce() callback starts becoming hard to scan, step back and ask whether map(), filter(), or a small loop would be clearer.
Sort safely with sort() and toSorted()
sort() mutates the original array, which surprises many developers.
const numbers = [10, 2, 5];
numbers.sort((a, b) => a - b);
// [2, 5, 10]Without a compare function, JavaScript sorts values as strings, which is often not what you want for numbers.
const wrong = [10, 2, 5].sort();
// [10, 2, 5] becomes ['10', '2', '5'] string-based orderingIf you want a sorted copy while preserving the original, use toSorted() where supported.
const original = [3, 1, 2];
const sorted = original.toSorted((a, b) => a - b);
// original: [3, 1, 2]
// sorted: [1, 2, 3]Extract part of an array with slice()
slice() returns a shallow copy of part of an array and does not mutate the original.
const items = ['a', 'b', 'c', 'd'];
const firstTwo = items.slice(0, 2);
// ['a', 'b']This is useful for pagination previews, limiting dashboard widgets, and creating copy-safe subsets.
For API-heavy interfaces, a solid follow-up is API Pagination Patterns Compared: Offset, Cursor, Keyset, and Token-Based.
Flatten nested arrays with flat() and flatMap()
const nested = [['red', 'blue'], ['green']];
const flat = nested.flat();
// ['red', 'blue', 'green']flatMap() is useful when each item maps to an array and you want the final result flattened by one level.
const sentences = ['hello world', 'array methods'];
const words = sentences.flatMap(sentence => sentence.split(' '));
// ['hello', 'world', 'array', 'methods']Join arrays and add items immutably
const base = ['html', 'css'];
const extended = [...base, 'javascript'];
// ['html', 'css', 'javascript']
const merged = base.concat(['typescript', 'node']);
// ['html', 'css', 'typescript', 'node']Spread syntax is often the most readable option for appending or combining arrays in UI state updates.
Remove duplicates with Set
This is not an array method, but it belongs in any practical array reference because it solves a common problem well.
const tags = ['api', 'css', 'api', 'javascript'];
const uniqueTags = [...new Set(tags)];
// ['api', 'css', 'javascript']For arrays of objects, deduplication usually needs a key:
const products = [
{ id: 1, name: 'Mouse' },
{ id: 1, name: 'Mouse' },
{ id: 2, name: 'Keyboard' }
];
const uniqueProducts = Array.from(
new Map(products.map(product => [product.id, product])).values()
);Chain methods carefully
Method chaining is concise when each step has one clear job.
const result = users
.filter(user => user.active)
.map(user => user.name.toUpperCase())
.toSorted();This reads well because the steps follow a plain-language sequence: keep active users, extract names, uppercase them, then sort.
If the chain becomes dense or the callbacks become multi-line, break the work into named variables. Clear intermediate steps are often easier to debug than a single long chain.
Common mistakes
Most array bugs are not syntax problems. They are method-choice problems.
Using map() when you mean filter()
map() transforms every item. It does not remove items.
const wrong = users.map(user => user.active ? user : null);
// Leaves null values in the arrayUse filter() if you want fewer items.
Forgetting that sort() mutates
This causes subtle bugs in stateful apps and shared utility code. If preserving the original matters, copy first or use toSorted().
const sorted = [...numbers].sort((a, b) => a - b);Skipping the initial value in reduce()
This can produce errors or edge cases, especially with empty arrays.
const total = prices.reduce((sum, price) => sum + price, 0);Adding the initial value makes the logic more predictable.
Expecting deep copies from array methods
Methods like slice(), map(), and spread syntax create shallow copies. Nested objects still point to the same references.
const original = [{ name: 'Ava' }];
const copy = [...original];
copy[0].name = 'Leo';
// original[0].name is also 'Leo'If nested data should be isolated, you need a deliberate deep-copy strategy appropriate to the data shape.
Overusing reduce()
reduce() can replace many methods, but that does not mean it should. Teams usually maintain code faster when intent is explicit.
Good rule: if a problem is naturally “transform,” “filter,” or “find,” use the matching method first.
Ignoring sparse arrays and missing values
Real-world data can contain undefined, null, or unexpected gaps. Be careful when chaining property access inside callbacks.
const names = users
.filter(user => user && user.name)
.map(user => user.name);This matters even more when data comes from configuration files, environment variables, or external APIs. See Node.js Environment Variables Guide: Validation, Defaults, and Secrets for defensive validation patterns that often pair well with array processing.
When to revisit
Use this cheat sheet as a living reference, especially when your codebase or runtime changes.
- Revisit when you adopt newer JavaScript runtimes: methods like
toSorted(),toReversed(), andtoSpliced()improve immutable workflows and are worth using when available. - Revisit when your team standard changes: some teams prefer explicit loops for complex logic; others encourage array chains for data transformation. Align with what your team can read quickly.
- Revisit when data shape changes: a flat list can become nested after an API update, pagination change, or CSV import adjustment.
- Revisit when performance becomes visible: for small and medium datasets, readability usually wins. For large datasets or hot rendering paths, re-check chained operations and repeated copies.
- Revisit when debugging state updates: if UI bugs look random, inspect whether a mutating method like
sort()orsplice()changed shared data.
A practical way to use this guide is to keep a short decision list nearby:
- If you need a transformed array, start with
map(). - If you need fewer items, start with
filter(). - If you need one match, use
find(). - If you need true or false, use
some()orevery(). - If you need one final value, use
reduce(). - If order changes, check whether mutation is acceptable before using
sort().
That small checklist covers a surprising amount of everyday frontend and backend JavaScript. And if your work often crosses into related cleanup and formatting tasks, you may also want to bookmark SQL Formatter Guide: How to Write More Readable Queries and Team Standards and Markdown Formatter and Linter Guide for Docs, READMEs, and Teams for the same kind of practical, reusable reference.
The best array method is usually the one that makes your intent obvious on the first read. When in doubt, optimize for clarity, avoid accidental mutation, and keep transformations small enough that future you can understand them without re-deriving the logic.