Chapter 3 introduced map, filter and reduce. Arrays have many more methods, and the single most important distinction to internalise is whether a method mutates the array in place or returns a new one — getting this wrong is a subtle, common source of bugs.
The big three, recap
const nums = [1, 2, 3, 4];nums.map(n => n * 2) // [2, 4, 6, 8] — transformnums.filter(n => n % 2) // [1, 3] — keepnums.reduce((a, n) => a + n, 0) // 10 — collapse
Searching arrays
| Method | Returns |
|---|---|
find | The first matching element (or undefined) |
findIndex | The index of the first match (or -1) |
some | true if any element passes |
every | true if all elements pass |
includes | true if a value is present |
const students = [{ name: "Aanya", placed: true },{ name: "Rohan", placed: false },];students.find(s => !s.placed) // { name: "Rohan", … }students.some(s => s.placed) // true — at least one placedstudents.every(s => s.placed) // false — not all placed[1, 2, 3].includes(2) // true
Sorting
sort is the big trap: by default it sorts as strings, and it mutates the array. For numbers, pass a comparator:
[10, 2, 1].sort() // [1, 10, 2] ❌ string sort![10, 2, 1].sort((a, b) => a - b) // [1, 2, 10] ✓ ascending[10, 2, 1].sort((a, b) => b - a) // [10, 2, 1] ✓ descending// Sort objects by a fieldstudents.sort((a, b) => a.name.localeCompare(b.name));// Don't mutate the source — copy first:const sorted = [...students].sort((a, b) => a.name.localeCompare(b.name));
Mutating vs non-mutating
const tools = ["Excel", "SQL"];const added = [...tools, "Python"]; // add (new array)const removed = tools.filter(t => t !== "SQL"); // remove (new array)const updated = tools.map(t => t === "SQL" ? "PostgreSQL" : t);
flat & flatMap
[[1, 2], [3, 4]].flat() // [1, 2, 3, 4][[1, [2]], [3]].flat(2) // [1, 2, 3] (depth 2)// flatMap = map then flatten one level["a b", "c d"].flatMap(s => s.split(" ")) // ["a", "b", "c", "d"]
Practice
Given an array of student objects, use find to get one by name, some/every to check placement, and a non-mutating sort (on a copy) to order by package. Confirm the original array is unchanged.
Key takeaways
- 01find/findIndex return the first match; some/every test any/all; includes checks presence.
- 02sort defaults to string order and mutates — pass (a, b) => a - b and sort a copy for numbers.
- 03Mutating: sort, reverse, push, pop, splice. Non-mutating: map, filter, slice, concat, spread.
- 04Prefer non-mutating methods in state-driven code (React) to avoid subtle bugs.
- 05flat/flatMap flatten nested arrays.
