67 entries · 8 sections
JavaScript Array Methods Cheat Sheet
Every array method worth knowing, grouped by what you are trying to do — create, add and remove, search, transform, reduce, sort, iterate — with a clear line between the methods that mutate the array and the ES2023 copying versions that do not.
Creating arrays
| Syntax | What it does |
|---|---|
Array.from(iterable) | Build an array from anything iterable or array-like, such as a NodeList. |
Array.from({ length: 5 }, (_, i) => i) | Generate [0, 1, 2, 3, 4] without an empty loop. |
Array.of(1, 2, 3) | An array of the arguments. Array.of(3) is [3] while Array(3) is three holes. |
Array.isArray(x) | The reliable array test — typeof [] returns "object". |
new Array(5).fill(0) | Five zeros. A bare new Array(5) has holes, which most methods skip. |
[...set] / [...str] | Spread any iterable into a new array. |
[...new Set(arr)] | Remove duplicate primitive values. |
arr.slice() | A shallow copy of an array. |
structuredClone(arr) | A deep copy that keeps Dates, Maps and Sets — no JSON round trip needed. |
Adding and removing (these mutate)
| Syntax | What it does |
|---|---|
arr.push(x) | Append one or more items; returns the new length. |
arr.pop() | Remove and return the last element. |
arr.unshift(x) | Prepend. Slower on large arrays because every index shifts. |
arr.shift() | Remove and return the first element. |
arr.splice(1, 2) | Remove two elements starting at index 1 and return them. |
arr.splice(1, 0, "x") | Insert without removing anything. |
arr.splice(1, 1, "x") | Replace exactly one element. |
arr.fill(0, 1, 3) | Overwrite indices 1 and 2 with 0. |
arr.copyWithin(0, 3) | Copy a run of elements over another position, in place. |
arr.length = 0 | Empty an array in place, including for every other reference to it. |
Copying instead of mutating (ES2023)
| Syntax | What it does |
|---|---|
arr.toSorted(fn) | A sorted copy; the original is untouched. |
arr.toReversed() | A reversed copy. |
arr.toSpliced(1, 2) | A spliced copy. |
arr.with(1, "x") | A copy with index 1 replaced. |
arr.at(-1) | The last element. at() accepts negative indices; arr[-1] does not. |
[...arr, x] | Append without mutating. |
arr.concat(other) | Join two arrays into a new one. |
Finding and testing
| Syntax | What it does |
|---|---|
arr.includes(x) | Does the array contain this value? Unlike indexOf, it finds NaN. |
arr.indexOf(x) | The first index of a value, or -1. |
arr.lastIndexOf(x) | The last index of a value, or -1. |
arr.find(fn) | The first element matching a predicate, or undefined. |
arr.findIndex(fn) | The index of the first match, or -1. |
arr.findLast(fn) / arr.findLastIndex(fn) | The same, searching from the end (ES2023). |
arr.some(fn) | True if at least one element passes. False for an empty array. |
arr.every(fn) | True if every element passes. True for an empty array. |
arr.filter(Boolean) | Drop every falsy value in one expression. |
Transforming
| Syntax | What it does |
|---|---|
arr.map(fn) | A new array of the same length with each element transformed. |
arr.map((x, i) => ...) | The index is the second argument, and the whole array the third. |
arr.filter(fn) | A new array of only the elements that pass. |
arr.flatMap(fn) | Map, then flatten one level. The clean way to do one-to-many. |
arr.flat() | Flatten one level of nesting. |
arr.flat(Infinity) | Flatten completely, however deep it goes. |
arr.reverse() | Reverse in place. Use toReversed() when you need a copy. |
arr.join(", ") | Join into a string. null and undefined become empty strings. |
arr.slice(1, 4) | Elements 1, 2 and 3 as a new array; the end index is exclusive. |
arr.slice(-2) | The last two elements. |
Reducing and grouping
| Syntax | What it does |
|---|---|
arr.reduce((acc, x) => acc + x, 0) | Fold to a single value. Always pass the initial value — an empty array throws without it. |
arr.reduceRight(fn, init) | The same, folding from the right. |
arr.reduce((m, x) => ({ ...m, [x.id]: x }), {}) | Index a list by key. For large arrays, mutate the accumulator instead of spreading. |
Math.max(...arr) | The largest value. Throws on very large arrays because of the argument limit. |
arr.reduce((a, b) => (a > b ? a : b)) | The largest value, safe at any size. |
arr.filter(fn).length | Count the matches. |
Object.groupBy(arr, x => x.type) | Group into a null-prototype object keyed by string (ES2024). |
Map.groupBy(arr, fn) | Group into a Map, so the keys can be objects or any other value. |
Sorting
| Syntax | What it does |
|---|---|
arr.sort() | Sorts by string conversion, so [10, 9] stays [10, 9]. Almost never what you want for numbers. |
arr.sort((a, b) => a - b) | Numeric, ascending. |
arr.sort((a, b) => b - a) | Numeric, descending. |
arr.sort((a, b) => a.name.localeCompare(b.name)) | Correct alphabetical order, accents and locale included. |
arr.sort((a, b) => a.x - b.x || a.y - b.y) | Sort by one key, then break ties with another. |
[...arr].sort(fn) | Sort a copy, because sort mutates the array it is called on. |
arr.toSorted(fn) | The built-in copying sort (ES2023). |
Iterating
| Syntax | What it does |
|---|---|
for (const x of arr) | The plain loop. break and continue work, and it is the fastest to read. |
arr.forEach(fn) | Call a function per element. You cannot break out of it, and it returns undefined. |
arr.entries() | An iterator of [index, value] pairs. |
arr.keys() / arr.values() | Iterators of the indices / the values. |
for (const [i, x] of arr.entries()) | Loop with the index, destructured. |
await Promise.all(arr.map(fn)) | Run async work over an array in parallel and wait for all of it. |
for (const x of arr) { await fn(x) } | Run async work strictly one at a time. arr.forEach(async ...) does neither. |
Worth knowing
- map, filter, slice, concat and the to* methods return new arrays; push, pop, splice, sort, reverse and fill change the array in place. Mixing them up is the source of most "why did my state change?" bugs in React — sort and reverse in particular mutate, so always spread first or use toSorted and toReversed.
- arr.forEach(async (x) => await f(x)) does not wait for anything. forEach ignores the promises it gets back, so the loop finishes instantly and the work continues unobserved. Use a for...of loop for sequential work or Promise.all(arr.map(f)) for parallel work.
- reduce is powerful and frequently the wrong tool. If you are reducing to an array, filter or flatMap says it more clearly; if you are reducing to an object keyed by id, Object.groupBy or a plain for...of loop reads better. Keep reduce for genuine folds like sums and merges.
Try a snippet instead of reading about it
Reference is faster when you can run the thing. Paste a snippet into AltF Code, the free in-browser editor — real syntax highlighting for HTML, CSS, JavaScript, Python, SQL, JSON and more, with HTML, CSS and JavaScript running live in the preview. No install and no sign-up.
Open the editorJavaScript Array Methods — common questions
- What is the difference between map and forEach?
- map returns a new array built from what your callback returns, so it is for transforming data. forEach returns undefined and exists only for side effects. If you are not using the result, forEach or a for...of loop states the intent better; if you are, map is the one you want.
- Which array methods mutate the original array?
- push, pop, shift, unshift, splice, sort, reverse, fill and copyWithin all mutate. Everything else — map, filter, slice, concat, flat, flatMap and the ES2023 toSorted, toReversed, toSpliced and with — returns a new array and leaves the original alone.
- How do I remove duplicates from an array?
- For primitives, [...new Set(arr)] is the shortest and fastest option. For objects you need a key: [...new Map(arr.map(o => [o.id, o])).values()] keeps the last object for each id, and swapping the map order keeps the first.
- Why does sort() put 10 before 9?
- Because the default sort converts every element to a string and compares those, and "10" sorts before "9". Pass a comparator to fix it: arr.sort((a, b) => a - b) for numbers ascending, or localeCompare for strings you want in human alphabetical order.