JavaScript Arrays and Objects Cheat Sheet

Comprehensive array, object, collection, and string manipulation patterns in JavaScript.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Array Creation
Array literal
const nums = [1, 2, 3];
Array.from iterable
const chars = Array.from("hello");
Build numeric range
const range = Array.from({ length: 5 }, (_, i) => i + 1);
Fill an array
const board = Array(9).fill(null);
Array.of
const values = Array.of(5);
## Array Transformation
Array map
const names = users.map((u) => u.name);
Array filter
const active = users.filter((u) => u.isActive);
Array reduce
const total = cart.reduce((sum, item) => sum + item.price, 0);
Array flat
const flattened = nested.flat(2);
Array flatMap
const tags = posts.flatMap((p) => p.tags);
Numeric sort
nums.sort((a, b) => a - b);
Sort objects by key
users.sort((a, b) => a.name.localeCompare(b.name));
toReversed copy
const newestFirst = items.toReversed();
toSorted copy
const sorted = nums.toSorted((a, b) => a - b);
toSpliced copy
const next = items.toSpliced(1, 2, "x", "y");
Group with reduce
const grouped = orders.reduce((acc, order) => {
  (acc[order.status] ??= []).push(order);
  return acc;
}, {});
Deduplicate array
const unique = [...new Set(values)];
## Array Mutation
Push item
items.push(newItem);
Pop last item
const last = items.pop();
Shift first item
const first = queue.shift();
Unshift item
queue.unshift(priorityItem);
Splice array
items.splice(1, 2, "replacement");
Slice array
const copy = items.slice(0, 3);
Concatenate arrays
const all = a.concat(b, c);
copyWithin
arr.copyWithin(1, 3, 5);
## Objects
Object.assign
const target = Object.assign({}, sourceA, sourceB);
Object.hasOwn
const own = Object.hasOwn(config, "port");
Object.freeze
const settings = Object.freeze({ theme: "dark" });
Object.seal
const draft = Object.seal({ title: "" });
Deep clone with structuredClone
const snapshot = structuredClone(state);
Quick object equality with JSON stringify
const same = JSON.stringify(a) === JSON.stringify(b);

# Works only when property order and JSON-safe values are acceptable.

## Strings
Trim whitespace
const normalized = input.trim();
Split and join
const slug = title.split(" ").join("-");
Replace all
const sanitized = text.replaceAll("_", "-");
startsWith / endsWith
file.startsWith("app-");
file.endsWith(".js");
Pad string
const code = String(id).padStart(6, "0");
localeCompare
names.sort((a, b) => a.localeCompare(b));
Iterate unicode-safe characters
for (const ch of "👍🏽JS") {
  console.log(ch);
}