javascript
const nums = [1, 2, 3];Comprehensive array, object, collection, and string manipulation patterns in JavaScript.
Build arrays from literals, ranges, and iterables.
const nums = [1, 2, 3];const chars = Array.from("hello");const range = Array.from({ length: 5 }, (_, i) => i + 1);const board = Array(9).fill(null);const values = Array.of(5);Map, filter, reduce, flatMap, sort, group, and dedupe.
const names = users.map((u) => u.name);const active = users.filter((u) => u.isActive);const total = cart.reduce((sum, item) => sum + item.price, 0);const flattened = nested.flat(2);const tags = posts.flatMap((p) => p.tags);nums.sort((a, b) => a - b);users.sort((a, b) => a.name.localeCompare(b.name));const newestFirst = items.toReversed();const sorted = nums.toSorted((a, b) => a - b);const next = items.toSpliced(1, 2, "x", "y");const grouped = orders.reduce((acc, order) => {
(acc[order.status] ??= []).push(order);
return acc;
}, {});const unique = [...new Set(values)];Find values, indices, and perform membership checks.
const user = users.find((u) => u.id === targetId);const idx = users.findIndex((u) => u.email === email);const hasDraft = posts.some((p) => p.status === "draft");const allValid = rows.every((row) => row.id != null);const hasRole = roles.includes("admin");const idx = tags.indexOf("urgent");Push, pop, shift, unshift, splice, slice, concat, and copyWithin.
items.push(newItem);const last = items.pop();const first = queue.shift();queue.unshift(priorityItem);items.splice(1, 2, "replacement");const copy = items.slice(0, 3);const all = a.concat(b, c);arr.copyWithin(1, 3, 5);Entries, cloning, freezing, deep access, and comparisons.
const target = Object.assign({}, sourceA, sourceB);const own = Object.hasOwn(config, "port");const settings = Object.freeze({ theme: "dark" });const draft = Object.seal({ title: "" });const snapshot = structuredClone(state);Works only when property order and JSON-safe values are acceptable.
const same = JSON.stringify(a) === JSON.stringify(b);Common string operations, unicode-safe iteration, and formatting.
const normalized = input.trim();const slug = title.split(" ").join("-");const sanitized = text.replaceAll("_", "-");file.startsWith("app-");
file.endsWith(".js");const code = String(id).padStart(6, "0");names.sort((a, b) => a.localeCompare(b));for (const ch of "👍🏽JS") {
console.log(ch);
}