JavaScript Array Methods Cheat Sheet (Live)
Array methods fall into two camps. Some change the array you call them on, such as push, pop, splice, sort and reverse. Others hand back a new array or value and leave the original alone, such as map, filter, slice, toSorted and reduce. Edit the list below and every method reruns on your values.
| Job | Method | Changes the original? |
|---|---|---|
| Transform every item | arr.map(fn) | No |
| Keep items that pass a test | arr.filter(fn) | No |
| Combine into one value | arr.reduce(fn, start) | No |
| First item that matches | arr.find(fn) | No |
| Add to the end | arr.push(x) | Yes |
| Sorted copy | arr.toSorted(fn) | No |
| Count the items | arr.length | Reading it, no; setting it, yes |
Updated
Most cheat sheets list method names with one canned example. Here the examples run against a list you control, so you can see what happens with duplicates, an empty list or a single item. Each row is tagged so you know at a glance whether a method rewrites your data, which is the source of many state bugs in React and similar libraries.
| Call | Group | Changes the original? | What it does |
|---|---|---|---|
| arr.length | Read | No | How many items |
| arr.at(0) | Read | No | First item |
| arr.at(-1) | Read | No | Last item, counting from the end |
| arr.includes("apple") | Search | No | true if the value is present |
| arr.indexOf("apple") | Search | No | First position of the value, or -1 |
| arr.lastIndexOf("apple") | Search | No | Last position of the value, or -1 |
| arr.find((s) => s.length > 4) | Search | No | First item that passes the test |
| arr.findIndex((s) => s.length > 4) | Search | No | Position of the first passing item |
| arr.findLast((s) => s.length > 4) | Search | No | Last item that passes the test |
| arr.some((s) => s.startsWith("k")) | Search | No | true if any item passes |
| arr.every((s) => s.length > 2) | Search | No | true if all items pass |
| arr.map((s) => s.toUpperCase()) | Transform | No | New array of each callback result |
| arr.filter((s) => s.length > 3) | Transform | No | New array of passing items |
| arr.reduce((n, s) => n + s.length, 0) | Transform | No | Folds the list into one value |
| arr.flatMap((s) => [s, s.length]) | Transform | No | map, then flatten one level |
| arr.slice(1, 3) | Transform | No | Copy of positions 1 and 2 |
| arr.concat(["plum"]) | Transform | No | New array with extra items on the end |
| arr.join(" | ") | Transform | No | One string with a separator |
| arr.toSorted() | Order | No | Sorted copy (text order) |
| arr.toReversed() | Order | No | Reversed copy |
| arr.toSpliced(1, 1) | Order | No | Copy with position 1 removed |
| arr.with(0, "lime") | Order | No | Copy with position 0 replaced |
| arr.sort() | Order | Yes | Sorts in place and returns the same array |
| arr.reverse() | Order | Yes | Reverses in place |
| arr.push("plum") | Add and remove | Yes | Adds to the end, returns the new length |
| arr.pop() | Add and remove | Yes | Removes the last item and returns it |
| arr.unshift("plum") | Add and remove | Yes | Adds to the start, returns the new length |
| arr.shift() | Add and remove | Yes | Removes the first item and returns it |
| arr.splice(1, 1) | Add and remove | Yes | Removes from position 1, returns the removed items |
| arr.fill("x", 1) | Add and remove | Yes | Overwrites from position 1 to the end |
| arr.copyWithin(0, 1) | Add and remove | Yes | Copies part of the array over another part |
| arr.keys() | Iterate | No | Iterator of positions (spread here to show it) |
| arr.entries() | Iterate | No | Iterator of [position, item] pairs |
Mutating methods and their copying twins
When you must not touch the original, for example React state or a function argument, swap the left column for the right.
| Changes the array | Returns a new array instead |
|---|---|
| arr.sort(fn) | arr.toSorted(fn) |
| arr.reverse() | arr.toReversed() |
| arr.splice(i, n, ...items) | arr.toSpliced(i, n, ...items) |
| arr[i] = value | arr.with(i, value) |
| arr.push(a, b) | [...arr, a, b] or arr.concat([a, b]) |
| arr.unshift(a) | [a, ...arr] |
| arr.pop() | arr.slice(0, -1) |
| arr.shift() | arr.slice(1) |
Chaining map, filter and reduce
Total of paid orders in one chain
Each step returns a fresh array, so the next method runs on it. The original orders list is never changed.
const orders = [
{ id: 1, paid: true, total: 40 },
{ id: 2, paid: false, total: 15 },
{ id: 3, paid: true, total: 25 },
];
const revenue = orders
.filter((o) => o.paid) // [{id:1...}, {id:3...}]
.map((o) => o.total) // [40, 25]
.reduce((sum, t) => sum + t, 0);
console.log(revenue); // 65Reading and setting length
length is a plain property. Shrinking it removes items from the end, which is why it counts as a change to the array.
const tags = ["css", "html", "js", "react"];
console.log(tags.length); // 4
tags.length = 2;
console.log(tags); // ["css", "html"]
tags.length = 0; // empties the array in place
console.log(tags); // []Updating React state without mutating
Copying methods give React a new array, so the component re-renders. Calling sort or push on the state array would not.
const [items, setItems] = useState(["b", "c", "a"]);
const add = (x) => setItems((prev) => [...prev, x]);
const remove = (i) => setItems((prev) => prev.toSpliced(i, 1));
const sortAZ = () => setItems((prev) => prev.toSorted());
Reading a chain from left to right
Because copying methods return arrays, you can call another method straight on the result. A chain like orders.filter(isPaid).map(toTotal).reduce(add, 0) reads as a sentence: keep paid orders, turn each into a number, add them up.
Long chains are easy to read but walk the list once per step. For a few thousand items this never matters; for very large data a single for...of loop that does all three jobs is quicker.
Search methods return different things
includes answers yes or no. indexOf and findIndex give a position, with -1 meaning not found. find and findLast give the item itself, or undefined. some and every answer a yes or no question about a test function.
includes and indexOf compare with strict equality, so they cannot find an object by its contents. Use find or some with a test function for that.
How it works
- Type a comma separated list in the box. Spaces around each item are trimmed.
- Every row recalculates. Methods that change the array run on a fresh copy each time, and the row shows both the return value and the array afterwards.
- Filter by name or pick a group such as Search or Transform to narrow the sheet.
- Scroll down for chaining examples, the length property and the mutating to copying swap table.
Tips
- In React state, prefer toSorted, toReversed, toSpliced and with over their in-place twins, because changing the old array means React may not notice the update.
- Give reduce a starting value. Without one, an empty array throws a TypeError.
- forEach always returns undefined and cannot be stopped with break. Use for...of, some or find when you need to stop early.
- map, filter and slice copy only one level deep. Objects inside the new array are the same objects as before.
Frequently asked questions
How do I get the length of an array in JavaScript?
Read arr.length. It is a property, not a method, so there are no brackets. It is one more than the highest index, which equals the item count for normal arrays. Setting arr.length = 0 empties the array, and setting a smaller number cuts items off the end.
What is the difference between map and forEach?
map builds a new array from whatever your function returns for each item, so you can assign it or chain more methods. forEach just calls your function and returns undefined. Use map when you want a result and forEach only for side effects such as logging.
Which array methods mutate the original array?
push, pop, shift, unshift, splice, sort, reverse, fill and copyWithin change the array in place. Setting length or an index directly does too. Everything else on this sheet leaves it untouched.
How do I remove an item from an array without changing it?
Use filter to drop by value, for example arr.filter((x) => x !== 'kiwi'), or toSpliced(index, 1) to drop by position. Both return a new array and leave the original as it was.
Why does map return undefined values?
Your callback did not return anything. An arrow function with curly braces needs an explicit return; write (x) => x * 2 or (x) => { return x * 2; }. A missing return gives undefined for that slot.
Related: Sort an array of objects, JavaScript loops compared, JavaScript objects guide, JavaScript string methods, JavaScript formatter.
Build your site free or see all free tools. On We.Inc you can build your site free, with no card and no trial needed to start. AI building is on paid plans from $19 a month.
More in Guides
- JavaScript Promises, Async/Await and Fetch
- JavaScript Date Format: Builder and Examples
- JavaScript Event Listeners: Click, Submit, Scroll and Delegation
- localStorage in JavaScript (with Working Examples)
- The JavaScript For Loop, and Which Loop to Use
- JavaScript Objects, and Why You See [object Object]
- Reload the Page with JavaScript: location.reload()
- Scroll to an Element with JavaScript
- Sort an array of objects in JavaScript
- JavaScript promises, async/await and fetch
- JavaScript date formatting
- JavaScript objects explained
Product
Who It's For
- For Agencies
- For Freelancers
- For Hosting Providers
- For SaaS Platforms
- For Startups
- For Financial Services
- For Healthcare
Features
Resources
- Blog
- Help Center
- Free Business Tools
- Free UI Components
- Website Templates
- Template Collections
- Website Examples
- Guides
- Comparisons
- Alternatives
- Best Lists
- Reviews
- Pricing Guides
- Use Cases
- Glossary & Guides
- Integrations
- Developers
- Benchmark
- Windows App