JS

Arrays

JavaScript · 12 entries

Creating Arrays

syntax
const arr = [a, b, c];
const arr = Array.from(iterable);
const arr = Array.of(elements);
example
const fruits = ["apple", "banana", "cherry"];
const range = Array.from({ length: 5 }, (_, i) => i + 1);
console.log(range);  // [1, 2, 3, 4, 5]

const filled = new Array(3).fill(0);
console.log(filled); // [0, 0, 0]

Note Array(5) creates 5 empty slots, not [5]. Use Array.of(5) for a single-element array. Be careful with fill() on objects -- all slots share the same reference.

Accessing Elements

syntax
arr[index]
arr.at(index)
example
const colors = ["red", "green", "blue", "yellow"];
console.log(colors[0]);     // "red"
console.log(colors.at(-1));  // "yellow"
console.log(colors.at(-2));  // "blue"

Note at() supports negative indexing. Bracket notation with negatives (arr[-1]) returns undefined because it looks for a property named "-1".

Adding and Removing Elements

syntax
arr.push(item)    // end
arr.pop()         // end
arr.unshift(item) // start
arr.shift()       // start
arr.splice(index, deleteCount, ...items)
example
const tasks = ["code", "test"];
tasks.push("deploy");       // ["code", "test", "deploy"]
tasks.unshift("plan");      // ["plan", "code", "test", "deploy"]
const removed = tasks.pop(); // "deploy"

// Insert at index 2
tasks.splice(2, 0, "review");
console.log(tasks); // ["plan", "code", "review", "test"]

Note push/pop are O(1). unshift/shift are O(n) because all indices must be renumbered. splice() mutates the original array.

map()

syntax
arr.map(callback(element, index, array))
example
const prices = [10, 25, 50];
const withTax = prices.map(p => +(p * 1.08).toFixed(2));
console.log(withTax);
output
[10.8, 27, 54]

Note map() returns a new array of the same length. If you do not need the return value, use forEach() instead.

filter()

syntax
arr.filter(callback(element, index, array))
example
const products = [
  { name: "Shirt", price: 25 },
  { name: "Jacket", price: 120 },
  { name: "Cap", price: 15 },
];
const affordable = products.filter(p => p.price < 50);
console.log(affordable.map(p => p.name));
output
["Shirt", "Cap"]

Note Returns a new array with elements that pass the test. The callback must return a truthy/falsy value.

reduce()

syntax
arr.reduce(callback(accumulator, current, index, array), initialValue)
example
const items = [
  { name: "Book", price: 12 },
  { name: "Pen", price: 3 },
  { name: "Bag", price: 45 },
];
const total = items.reduce((sum, item) => sum + item.price, 0);
console.log(total);
output
60

Note Always provide an initial value (second argument). Without it, reduce uses the first element and can throw on empty arrays.

find() and findIndex()

syntax
arr.find(callback)
arr.findIndex(callback)
arr.findLast(callback)
arr.findLastIndex(callback)
example
const users = [
  { id: 1, name: "Ava" },
  { id: 2, name: "Bo" },
  { id: 3, name: "Ava" },
];
console.log(users.find(u => u.name === "Ava"));     // { id: 1, name: "Ava" }
console.log(users.findLast(u => u.name === "Ava")); // { id: 3, name: "Ava" }
console.log(users.findIndex(u => u.id === 2));       // 1

Note find() returns the first match or undefined. findLast() (ES2023) searches from the end. Both return the element, not a boolean.

Sorting

syntax
arr.sort(compareFn)
arr.toSorted(compareFn)
example
const nums = [40, 1, 5, 200];
// WRONG: default sort is lexicographic
console.log([...nums].sort());             // [1, 200, 40, 5]
// CORRECT: numeric sort
console.log([...nums].sort((a, b) => a - b)); // [1, 5, 40, 200]

// Non-mutating sort (ES2023)
const sorted = nums.toSorted((a, b) => b - a);
console.log(sorted); // [200, 40, 5, 1]
console.log(nums);   // [40, 1, 5, 200] (unchanged)

Note sort() MUTATES the array and defaults to string comparison. Always pass a compare function for numbers. Use toSorted() for a non-mutating alternative.

flat() and flatMap()

syntax
arr.flat(depth)
arr.flatMap(callback)
example
const nested = [[1, 2], [3, [4, 5]]];
console.log(nested.flat());    // [1, 2, 3, [4, 5]]
console.log(nested.flat(2));   // [1, 2, 3, 4, 5]

const sentences = ["hello world", "good morning"];
const words = sentences.flatMap(s => s.split(" "));
console.log(words); // ["hello", "world", "good", "morning"]

Note flatMap() is equivalent to map() followed by flat(1) but more efficient. Use flat(Infinity) to flatten any depth.

includes(), some(), every()

syntax
arr.includes(value)
arr.some(callback)
arr.every(callback)
example
const perms = ["read", "write", "delete"];
console.log(perms.includes("write"));  // true

const ages = [22, 17, 30, 15];
console.log(ages.some(a => a < 18));   // true
console.log(ages.every(a => a >= 18)); // false

Note includes() uses strict equality (===) and works with NaN. some() short-circuits on the first true; every() short-circuits on the first false.

Non-Mutating Alternatives (ES2023)

syntax
arr.toSorted(fn)
arr.toReversed()
arr.toSpliced(start, deleteCount, ...items)
arr.with(index, value)
example
const original = [3, 1, 4, 1, 5];

const reversed = original.toReversed();
console.log(reversed);  // [5, 1, 4, 1, 3]

const replaced = original.with(2, 99);
console.log(replaced);  // [3, 1, 99, 1, 5]

console.log(original);  // [3, 1, 4, 1, 5] (untouched)

Note These return new arrays, leaving the original unchanged. Ideal for immutable state patterns (React, Redux, etc).

Deep Cloning Arrays

syntax
structuredClone(value)
example
const original = [
  { name: "Ava", scores: [90, 85] },
  { name: "Leo", scores: [78, 92] },
];
const clone = structuredClone(original);
clone[0].scores.push(100);

console.log(original[0].scores); // [90, 85] (not affected)
console.log(clone[0].scores);    // [90, 85, 100]

Note structuredClone handles nested objects, arrays, Maps, Sets, Dates, RegExps, and more. Does NOT clone functions, DOM nodes, or prototypes.