JavaScript Array Methods — map, filter, reduce and More
Quick reference for map, filter, reduce, and more — with copy-paste examples
Transform .map() — transform each element
Creates a new array by calling a function on every element in the original array. Does not mutate the original.
const doubled = numbers.map(n => n * 2);const names = users.map(u => u.name);map() when you need to transform data. Avoid mutating the original array — it returns a new one.Transform .filter() — select elements by condition
Creates a new array with all elements that pass the test implemented by the provided function.
const evens = numbers.filter(n => n % 2 === 0);const active = users.filter(u => u.active);filter() returns a subset. Original array is unchanged.Aggregate .reduce() — accumulate to single value
Executes a reducer function on each element, resulting in a single output value. Extremely flexible.
const sum = numbers.reduce((acc, n) => acc + n, 0);const max = numbers.reduce((a, b) => Math.max(a, b));Aggregate .reduceRight() — reduce from right to left
Works like reduce() but starts from the last element and moves backward.
const flattened = [].concat(...arrays.reduceRight((a, b) => [b, ...a]));Search .find() — first matching element
Returns the first element that satisfies the provided testing function. Returns undefined if none found.
const user = users.find(u => u.id === 123);find() when you expect at most one match. Use filter() for multiple matches.Search .findIndex() — index of first match
Returns the index of the first element that satisfies the testing function. Returns -1 if not found.
const idx = users.findIndex(u => u.email === 'test@example.com');Search .includes() — check if value exists
Determines whether an array includes a certain value among its entries. Simple and readable.
const hasAdmin = roles.includes('admin');=== for comparison. For objects, checks reference equality, not content.Search .indexOf() — first index of value
Returns the first index at which a given element can be found. Returns -1 if not present.
const idx = items.indexOf('apple');indexOf() uses === and does not work with NaN. Use findIndex() for complex checks.Search .lastIndexOf() — last index of value
Returns the last index at which a given element can be found. Searches backwards from the end.
const last = data.lastIndexOf('error');Boolean .some() — at least one passes
Tests whether at least one element passes the test. Short-circuits on first match (efficient).
const hasAdult = users.some(u => u.age >= 18);filter().length > 0.Boolean .every() — all pass
Tests whether all elements pass the test. Short-circuits on first failure.
const allActive = users.every(u => u.active);every() returns true for empty arrays (vacuous truth).Mutation Methods (modify original array)
arr.push(x) ? returns new length
arr.pop() ? returns removed element
arr.unshift(x) ? returns new length
arr.shift() ? returns removed element
slice(), concat(), or spread for immutable patterns.Manipulate .slice() — extract portion (non-mutating)
Returns a shallow copy of a portion of an array. Does not modify the original.
const first3 = arr.slice(0, 3); // [0, 3)const tail = arr.slice(1); // from index 1 to endconst copy = arr.slice(); // clone entire arrayManipulate .splice() — change array in-place
Changes array contents by removing/replacing existing elements and/or adding new ones. Mutates original. Returns removed elements.
// Remove 1 element at index 2
const removed = arr.splice(2, 1);// Insert without removing
arr.splice(2, 0, 'new');// Replace 1 element at index 1
arr.splice(1, 1, 'replacement');splice() alters the source array. Use slice() for non-destructive.Manipulate .concat() — merge arrays
Merges two or more arrays. Returns a new array. Does not mutate originals.
const merged = arr1.concat(arr2, arr3);const withExtra = arr.concat('a', 'b');[...arr1, ...arr2]. concat() also flattens one level automatically.Manipulate .join() — array to string
Joins all elements into a string, separated by the specified separator. Default separator is comma.
const csv = arr.join(',');const sentence = words.join(' ');const path = parts.join('/');Manipulate .split() — string to array (String method)
Splits a string into an array of substrings using the specified separator. String method, not Array method.
const parts = 'a,b,c'.split(',');const words = sentence.split(' ');split() is on String.prototype, not Array. Remember: arrays use join(), strings use split().Manipulate .reverse() — reverse in-place
Reverses the array in place. Mutates original and returns it.
const reversed = arr.slice().reverse(); // safe: copy firstreverse() mutates. To avoid side effects: [...arr].reverse() or arr.slice().reverse().Manipulate .sort() — sort in-place
Sorts array elements in place. Default sort is lexicographic (string) order. Always provide a compare function for numbers.
// Numeric ascending
arr.sort((a, b) => a - b);// Descending
arr.sort((a, b) => b - a);// By property
users.sort((a, b) => a.name.localeCompare(b.name));sort() mutates. For immutable: [...arr].sort(compare). Default sort breaks numbers: [10,2,1].sort() ? [1,10,2].Iterate .forEach() — execute for each element
Executes a provided function once for each array element. No return value (undefined). Cannot be chained.
users.forEach(u => console.log(u.name));arr.forEach((val, idx, array) => { /* ... */ });forEach() for side effects only. For transformations, use map(). Cannot break early — use for...of or some() if you need to exit early.Iterators (for...of loops)
for (const [i, v] of arr.entries()) { }
for (const i of arr.keys()) { }
for (const v of arr.values()) { }
for...of or Array.from(). entries() gives [index, value] pairs..length
arr.length — number of elementsNot a method; a property. Updating
length truncates or extends array.
Info Array.isArray() — check if value is array
Determines whether the passed value is an array. Safer than instanceof Array (works across frames).
if (Array.isArray(value)) { /* safe */ }typeof [] === 'object' — always use Array.isArray() to reliably detect arrays.Manipulate .flat() / .flatMap() — flatten arrays
flat() creates a new array with all sub-array elements concatenated recursively. flatMap() maps then flattens one level.
const flat = nested.flat(); // depth=1 defaultconst deep = nested.flat(2); // depth 2const result = arr.flatMap(x => [x, x * 2]);flatMap(flatMap) is faster than map().flat(). Great for 1-to-many transformations.JavaScript array methods — what each one does and when to use it
Array methods in JavaScript are one of those things where knowing the right one saves you writing 10 lines of manual loop code. Here's the practical breakdown: what each method does, what it returns, and when you'd actually reach for it.
Transforming arrays
| Method | Returns | Use when |
|---|---|---|
| map(fn) | New array, same length | Transform every element — e.g. format dates, extract a field |
| filter(fn) | New array, shorter or equal | Keep only elements that pass a condition |
| reduce(fn, init) | Single value (any type) | Sum, count, group, build an object from an array |
| flatMap(fn) | Flattened new array | Map + flatten in one step — useful when map returns arrays |
| flat(depth) | New flattened array | Flatten nested arrays — flat(Infinity) for any depth |
Finding elements
| Method | Returns | Note |
|---|---|---|
| find(fn) | First matching element or undefined | Stops at first match — faster than filter for single items |
| findIndex(fn) | Index or -1 | When you need the position, not the value |
| includes(val) | boolean | Simple presence check — uses strict equality |
| some(fn) | boolean | True if at least one element passes the test |
| every(fn) | boolean | True only if all elements pass the test |
Sorting and ordering
sort((a, b) => a - b)— numeric sort ascending (default sort is alphabetical, which sorts [10, 9, 2] wrong)sort((a, b) => b - a)— numeric sort descendingtoSorted(fn)— non-mutating sort (returns new array, original unchanged) — ES2023reverse()— reverses in-place (mutates original)toReversed()— non-mutating reverse — ES2023
Complete Developer Toolkit
JavaScript array methods are most useful when working with API data and UI state. After using filter(), map(), or reduce() to transform API data, use our JSON formatter to validate the resulting JSON structure before passing it to your components. Our regex tester is closely paired with array methods — filter() combined with regex is one of the most common patterns for searching arrays of strings, and you can test those patterns here before writing the code. Our API response simulator generates mock JSON arrays so you can prototype your array method logic against realistic data.
When your transformed array data needs to be serialized for URL query parameters, our URL encoder handles the encoding, and our Base64 encoder converts array data for transport in headers or storage. After writing your array processing logic, our JS minifier compresses it for production. The diff checker is useful for comparing two versions of array transformation logic to see what changed. Our Python cheat sheet covers the equivalent list comprehension and functional methods in Python — handy when porting JS array logic to a backend Python service. The Core Web Vitals guide covers how expensive array operations on large datasets can hurt INP scores.