Day 2 · Concept 04
Arrays
Dynamic, ordered, zero-indexed, can hold anything. Modern JS lives in .map / .filter / .reduce — chain them instead of writing for.
1 · The basics
const nums = [1, 2, 3, 4, 5];
console.log(nums.length); // 5
console.log(nums[0]); // 1
console.log(nums.at(-1)); // 5 — negative indexing
nums.push(6); // append, returns new length
nums.unshift(0); // prepend
const last = nums.pop(); // remove last
const first = nums.shift(); // remove first
console.log(nums); // [1, 2, 3, 4, 5]
console.log(first, last); // 0 62 · The chain — map / filter / reduce
const items = [
{ name: "apple", price: 1.0, stock: 10 },
{ name: "banana", price: 0.5, stock: 0 },
{ name: "cherry", price: 3.0, stock: 5 },
];
const inStockTotal = items
.filter(x => x.stock > 0)
.map(x => x.price * x.stock)
.reduce((a, b) => a + b, 0);
console.log(inStockTotal); // 1.0*10 + 3.0*5 = 25Reads top-to-bottom: keep what matches, transform each, fold into one value. No mutation; the original items is unchanged.
3 · Method cheat sheet
| Method | Does what | Mutates? |
|---|---|---|
.map(fn) | Transform each → new array | No |
.filter(fn) | Keep matches → new array | No |
.reduce(fn, init) | Fold into a single value | No |
.find(fn) | First element matching | No |
.some(fn) / .every(fn) | Any / all match | No |
.includes(x) | Has this value? | No |
.flat() / .flatMap(fn) | Flatten one level | No |
.sort(fn) | In-place sort | Yes |
.reverse() | In-place reverse | Yes |
.splice(i, n, ...items) | Remove / insert at index | Yes |
.slice(start, end) | Sub-array (no end = to end) | No |
4 · Sorting — the comparator gotcha
// Default sort converts to STRING — counterintuitive for numbers
const nums = [10, 1, 5, 21, 3];
console.log([...nums].sort()); // [1, 10, 21, 3, 5] ← string order
// Always pass a comparator for numbers
console.log([...nums].sort((a, b) => a - b)); // ascending
console.log([...nums].sort((a, b) => b - a)); // descendingUse [...arr].sort(...) to copy first — sort mutates.
5 · Common mistakes
- Forgetting
.sortmutates. Copy with[...arr]orarr.slice()first. - Default sort on numbers. String order. Always supply a comparator.
- Skipping the initial value in
reduce.[].reduce(fn)throws.[].reduce(fn, 0)returns 0. - Using
forEachwhen you wantedmap.forEachreturnsundefined.
6 · When it clicks
- You write
.filter().map().reduce()faster thanfor (let i.... - You spot which array methods mutate by reflex.
arr.at(-1)replacesarr[arr.length - 1].
Found this useful?