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.

Everyday array jobs and the method for each
JobMethodChanges the original?
Transform every itemarr.map(fn)No
Keep items that pass a testarr.filter(fn)No
Combine into one valuearr.reduce(fn, start)No
First item that matchesarr.find(fn)No
Add to the endarr.push(x)Yes
Sorted copyarr.toSorted(fn)No
Count the itemsarr.lengthReading 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.

Every method on this sheet
CallGroupChanges the original?What it does
arr.lengthReadNoHow many items
arr.at(0)ReadNoFirst item
arr.at(-1)ReadNoLast item, counting from the end
arr.includes("apple")SearchNotrue if the value is present
arr.indexOf("apple")SearchNoFirst position of the value, or -1
arr.lastIndexOf("apple")SearchNoLast position of the value, or -1
arr.find((s) => s.length > 4)SearchNoFirst item that passes the test
arr.findIndex((s) => s.length > 4)SearchNoPosition of the first passing item
arr.findLast((s) => s.length > 4)SearchNoLast item that passes the test
arr.some((s) => s.startsWith("k"))SearchNotrue if any item passes
arr.every((s) => s.length > 2)SearchNotrue if all items pass
arr.map((s) => s.toUpperCase())TransformNoNew array of each callback result
arr.filter((s) => s.length > 3)TransformNoNew array of passing items
arr.reduce((n, s) => n + s.length, 0)TransformNoFolds the list into one value
arr.flatMap((s) => [s, s.length])TransformNomap, then flatten one level
arr.slice(1, 3)TransformNoCopy of positions 1 and 2
arr.concat(["plum"])TransformNoNew array with extra items on the end
arr.join(" | ")TransformNoOne string with a separator
arr.toSorted()OrderNoSorted copy (text order)
arr.toReversed()OrderNoReversed copy
arr.toSpliced(1, 1)OrderNoCopy with position 1 removed
arr.with(0, "lime")OrderNoCopy with position 0 replaced
arr.sort()OrderYesSorts in place and returns the same array
arr.reverse()OrderYesReverses in place
arr.push("plum")Add and removeYesAdds to the end, returns the new length
arr.pop()Add and removeYesRemoves the last item and returns it
arr.unshift("plum")Add and removeYesAdds to the start, returns the new length
arr.shift()Add and removeYesRemoves the first item and returns it
arr.splice(1, 1)Add and removeYesRemoves from position 1, returns the removed items
arr.fill("x", 1)Add and removeYesOverwrites from position 1 to the end
arr.copyWithin(0, 1)Add and removeYesCopies part of the array over another part
arr.keys()IterateNoIterator of positions (spread here to show it)
arr.entries()IterateNoIterator 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.

In place versus copy
Changes the arrayReturns 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] = valuearr.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); // 65

Reading 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

  1. Type a comma separated list in the box. Spaces around each item are trimmed.
  2. 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.
  3. Filter by name or pick a group such as Search or Transform to narrow the sheet.
  4. 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

More on this topic

Product

Who It's For

Features

Resources

Company

View Sitemap