04 / 20 · Day 2
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

js arrays.js
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 6

2 · The chain — map / filter / reduce

js chain.js
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 = 25

Reads top-to-bottom: keep what matches, transform each, fold into one value. No mutation; the original items is unchanged.

3 · Method cheat sheet

MethodDoes whatMutates?
.map(fn)Transform each → new arrayNo
.filter(fn)Keep matches → new arrayNo
.reduce(fn, init)Fold into a single valueNo
.find(fn)First element matchingNo
.some(fn) / .every(fn)Any / all matchNo
.includes(x)Has this value?No
.flat() / .flatMap(fn)Flatten one levelNo
.sort(fn)In-place sortYes
.reverse()In-place reverseYes
.splice(i, n, ...items)Remove / insert at indexYes
.slice(start, end)Sub-array (no end = to end)No

4 · Sorting — the comparator gotcha

js sort.js
// 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));   // descending

Use [...arr].sort(...) to copy first — sort mutates.

5 · Common mistakes

  • Forgetting .sort mutates. Copy with [...arr] or arr.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 forEach when you wanted map. forEach returns undefined.

6 · When it clicks

  • You write .filter().map().reduce() faster than for (let i....
  • You spot which array methods mutate by reflex.
  • arr.at(-1) replaces arr[arr.length - 1].
Found this useful?